检查jsp文件中的servlet会话属性值

Mar*_*rta 10 jsp servlets

我有一个没有框架的java应用程序.它由用于视图的jsp文件和用于业务逻辑的servlet组成.我必须设置用户会话是带有firstName参数的servlet.在jsp文件中,我需要检查我的firstName参数是否有值.如果设置了firstName参数,我需要在jsp文件中显示一些html.如果没有设置,我需要在jsp文件中显示不同的html.

Servlet.java:

HttpSession session = request.getSession();
session.setAttribute("firstName", customer.getFristName());
String url = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
Run Code Online (Sandbox Code Playgroud)

header.jsp中:

// Between the <p> tags bellow I need to put some HTML with the following rules
// If firstName exist: Hello ${firstName} <a href="logout.jsp">Log out</a>
// Else: <a href="login.jsp">Login</a> or <a href="register.jsp">Register</a>

<p class="credentials" id="cr"></p>
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

更新:

这是我在JSTL上发现的一个很棒的教程,万一有人需要它:http: //www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

Isa*_*aac 9

<% if (session.getAttribute("firstName") == null) { %>
    <p> some content </p>
<% } else {%>
    <p> other content </p>
<% } %>
Run Code Online (Sandbox Code Playgroud)

  • 乱?显然你做错了什么.使用JSTL/EL就像`<c:if test ="$ {not empty firstname}"> <p> some content </ p> </ c:if> <c:if test ="$ {empty firstname }"> <p>其他内容</ p> </ c:if>`.我不确定那是多么混乱. (3认同)