In my Dynamic Web Application (working in Eclipse, with Tomcat 7 server), my pages have the same header, which includes the username of the currently logged in user.
Rather than having the header appear identically on each page, I extracted and included
<%# include file="../includes/head.jsp" %>
to the top of each .jsp.
But I noticed a problem. In the Servlet files I created I have a variation of (depending on the jsp page):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login doGet");
request.setAttribute("name", "value");
request.getRequestDispatcher("resources/jsp/login.jsp").forward(request, response);
}
However, in the head.jsp file,
${request.getAttribute("name") != null ? "Logged In" : "Not logged in"}
is causing "Not logged in" to appear when I'm expecting it to say "Logged In" (because I did pass an attribute called "name".
Any ideas what is going on?
<%= request.getAttribute("name") == null ? "Logged In" : "Not logged in" %>
Works because you have used the scriptlets to print the request attributes in the traditional way. However it is considered as bad practice . see How to avoid Java code in JSP files?
${request.getAttribute("name") == null ? "Logged In" : "Not logged in"}
Doesnt work because you have incorrect syntax of Expression Language
so either use jstl as #user23123412 suggested or write it as ,
${name == null ? "Logged In" : "Not logged in"}
to evaluate using EL
Hope this helps !!
You should use request.getSession().setAttribute("name", "value");
I got this to work eventually by using this
<%= request.getAttribute("name") == null ? "Logged In" : "Not logged in" %>
instead of the original
${request.getAttribute("name") == null ? "Logged In" : "Not logged in"}
I tried this after I saw that this is another way to write expressions. I have no idea why this way works and the other way doesn't and would love if some could add an explanation.
You could also use JSTL for this manner. Its better way to use jstl rather than scriptlets.
<c:out value="${empty name ? 'Logged In' : 'Not logged in' }" />
Related
I want to perform an action on a JSP if redirected from a specific servlet only else do nothing.Is it possible?
In my JSP there are different errors defined. This JSP calls a servlet (with contentType as application/pdf) which opens in a new tab and searches for a PDF for 25 seconds and then if PDF is not found redirects to same JSP which shows the error message "File not found". I want to show the error if called from servlet only else do nothing.
JSP Code:
<%}else if(hPP!=null && hPP.get("errorcode")!=null && hPP.get("errorcode").toString().equalsIgnoreCase("Issue")){%>
<c:if test="${cameFromServlet}">
<div class="SplInputField">
<label class="FontBlod">Download fail</label>
</div>
</c:if>
servlet code
if (content == null) {
request.setAttribute("cameFromServlet", true);
String redirectJspUrl = request.getParameter("homeRedirect");
String strReceiptPage =
redirectJspUrl.substring(0, redirectJspUrl.lastIndexOf("/")) +
"/GetQReceiptPage";
response.sendRedirect(strReceiptPage);
}
Add an attribute to the request in the servlet like this
httpservletRequest.setAttribute("cameFromServlet", true)
then in your JSP check for it
<c:if test="${cameFromServlet}">
DO STUFF HERE
</c:if>
EDIT:
What you have done in your edit will not work, since you are doing a redirect. Which means the browser is sent a 302 response to tell it to issue another request against the new url. Do you have a specific requirement to change the url for the user? If so you will need to add the cameFromServlet attribute to the session instead - like this:
req.getSession().setAttribute("cameFromServlet", true);
Bare in mind though, that cameFromServlet attribute will remain on the session until you unset it so if there was another time that jsp page is shown you will run into problems unless you do something to unset it - either by introducing another servlet in the middle and moving it from the session to the request - thus simulating Springs flash map behaviour or unset it in the JSP after you have used it - like this:
<c:remove var="cameFromServlet" scope="session" />
If you do not need the URL to change for the user, you can change your servlet code to make use of a request dispatcher (what I thought you were doing)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/yourjsp.jsp");
requestDispatcher.forward(req, resp);
I have a simple login page (login.jsp) and I'm checking it against a database to verify user credentials. This is just for testing, not for making an actual site.
In the verification servlet where the values are checked against the DB values, if there is not a match I do a
response.getRedirect("login.jsp?loginfailed=true");
This, obviously, sends me to
localhost:8080/blahblahblahblah/login.jsp?loginfailed=true
which is what I want. But then, in the jsp file, I do
<%
if(request.getParameter("loginfailed") == "true")
{
out.println("login failed");
}
%>
I'm well aware that I should replace this with JSTL, it's just easier for me to use scriptlets at first for control flow and I change them out once the logic works.
I just don't know why it is not working right now. What am I doing wrong?
Basically when credentials DO match DB values, it redirects to a success page. But if they don't, it redirects back to login.jsp with a URL param, and I want to print some text that says the login failed so the user doesn't have to look at the url to see that.
your redirection should be in this way.
response.sendRedirect(request.getContextPath()+"/login.jsp?loginfailed=true");
I am developing an application with spring 3 struts 2 and hibernate. After login only i have to display the pages
It is working fine. when i testing i found the big mistake
that is i copy the url of the page which needs to display only to logged-in user
and paste it in other browser means it is displaying the page without login.
<%
String userId= (String)session.getAttribute("userId");
System.out.println(userId);
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
%>
I have included this for all jsp. I know this is not a best practice. Is any better option available?
How would i overcome this error?
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
}
should probably have a return in there to prevent rendering the page content:
if(userId == null || userId.equals("") ){
response.sendRedirect("login.jsp");
return;
}
Nothing in the javadoc suggests that sendRedirect causes abrupt exit or causes the response body to not be shipped to the client.
What is probably happening is that your response contains a redirect header, but also contains the page content which you might not have meant to send.
I am still at education so do know how good is my solution , but i did not crash so hope it is correct
and it is quite similar to #muthu 's code
I had used JPA-eclipselink and Struts2
Action Class
String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password";
Query checkLoginQuery = em.createQuery(checkLogin);
checkLoginQuery.setParameter("username", loginUsername);
checkLoginQuery.setParameter("password", loginPassword);
userEntity = (UserEntity) checkLoginQuery.getSingleResult();
Map sessionMap = ActionContext.getContext().getSession();
sessionMap.put("userEntity", userEntity);
JSP -> all jsp pages have this(bug:affected if session is not killed when browser is not closed )
<%# taglib prefix="s" uri="/struts-tags" %>
<s:if test="%{#session.userEntity == null}">
<jsp:forward page="login.jsp"/>
</s:if>
Correct me if I am wrong
Quoting this page
Both and RequestDispatcher.forward() are what I refer to as "server-side" redirects
The response.sendRedirect() is what I call a "client-side" redirect.
so a server side forward looks more safe to me , maybe I am wrong (I am sorry if I am miss interpreting it ,not worked in real life projects yet)
I want to prevent user from going back to Login page if he already logged in
if (req.getRequestURI().indexOf("Login.jsp") != -1 || req.getRequestURI().indexOf("LoginE.jsp") != -1) {
System.out.println("trtying to go to login");
//what should I write here to redirect the user to the page he was already in ??
}
Just check if the user is already logged in and then redirect to the desired target page. Assuming that user represents the logged-in user which you've grabbed from the session, here's an example:
if (req.getRequestURI().indexOf("Login.jsp") != -1 || req.getRequestURI().indexOf("LoginE.jsp") != -1) {
if (user != null) {
response.sendRedirect("already-logged-in.jsp");
return;
}
}
where that page look something like
<p>You appears to be already logged in. If you want to login as someone else,
please use the logout link to logout, or navigate to a
different page by menu on the left hand side.</p>
I would also hide the link to the login page altogether when the user is already logged in, just to prevent that the user clicks that accidently or something.
<c:if test="${empty user}">
Login
</c:if>
Unrelated to the concrete problem, what's that with Login.jsp and LoginE.jsp? Is the one in native language and the other in English? You may want to invest some time in JSTL localization facilities. How to internationalize a Java web application?
Depending on how your user got to the Login.jsp request, you may have lost the info about the previous request. Have you tried looking at the "Referer" header to see if the previous page is in there? You could use req.getHeaders("Referer");
If there is no referrer information, you will have to manage a Session attribute for the user, called something like "lastRequestURL". That way you can retrieve it in your code above using: req.getSession().getAttribute("lastRequestURL") and redirect the user to that value.
I need to pass a variable from Admin.java file to index.jsp. I get the value when I print it in Admin.java. I need to pass that value to another variable which needs to be sent to index.jsp. This new variable gets null value.
The code in Admin.java is
public string static rest;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
System.out.println("The value of rest is "+rest);
request.getRequestDispatcher("index.jsp").forward(request, response);
if(res != null)
{
request.getSession().setAttribute("access", true);
System.out.println("Admin:doGet:login:true");
response.getWriter().write("existsnoadmin");
return;
}
Output:
The value of res been passed is C Language.
The value of rest is null.
As per the questions asked in stack overflow we need to use forward or redirect when we need to send the value to jsp page. But in my case, I am trying to return value from a function so I do not know whether the way I am trying to do in the above code is right or not.
The code in index.jsp is:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
The output is that I am getting the alert box which says "existsnoadmin".
But I am not able to get the value of rest here nor in Admin.java.
What is the mistake I have done here? Please help.
Regards,
Archana.
You say that the code in the JSP is this:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
I'm having problems understanding what this really means.
If the above code is Java code that appears inside scriptlet tags <% ... %>, then I don't understand how alert(response); is showing you anything. In fact, it should give you a compilation error in the JSP.
On the other hand, if the above is Javascript code that is embedded in the page that the JSP generates, then
request.getAttribute("rest") cannot possibly work ... because the request object that you set the attribute on does not exist in the web browser, and
out.println(...) cannot work because the JspWriter does not exist in the web browser.
Either you have not transcribed the JSP excerpt accurately, or your Java and/or Javascript doesn't make sense.
Based on your comment, I think you need the following.
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'<% request.getAttribute("rest") %>');
// The value obtained by the admin.java is <% request.getAttribute("rest") %>
}
Or if you want to get rid of the scriplet stuff ...
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'${requestScope.rest"}');
// The value obtained by the admin.java is ${requestScope.rest"}
}
If you want the stuff that I've turned into a // JS comment to be visible on the page, you been to move it to some content part of the HTML. Currently it is (I assume) inside a <script> element, and therefore won't be displayed.
The key to all of this black magic is understanding what parts of a JSP are seen/evaluated by what:
JSP directives e.g. <# import ...> are evaluated by the JSP compiler.
Stuff inside scriptlet tags e.g. <% ... %>, EL expressions e.g. ${...} or JSTL tags e.g. <c:out ...\> gets evaluated when the JSP is "run".
Anything generated by the JSP (HTML content, embedded Javascript) is displayed / executed in the user's browser after the HTTP response has been received.
Now is it neccessary to use the request.dispatcher....forward command in admin.java.
Your primary servlet can do one of two things.
It can use the request dispatcher to forward the request to your JSP. If it does this it can forward additional values by setting request attributes.
It can open the response output stream and write stuff to it.
It should not attempt to do both! (I'm not sure exactly what will happen, but it is likely to result in a 500 Internal Error.)