0

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?

Santhosh
  • 8,181
  • 4
  • 29
  • 56
C H
  • 3
  • 3

4 Answers4

0

You should use request.getSession().setAttribute("name", "value");

StackFlowed
  • 6,664
  • 1
  • 29
  • 45
0

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.

C H
  • 3
  • 3
0

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' }" />
Ken de Guzman
  • 2,790
  • 1
  • 19
  • 33
0
<%= 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 !!

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56