Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking servlet session attribute value in jsp file

Tags:

jsp

servlets

I have a no framework java application. It consists of jsp files for view and servlets for the business logic. I must set the user session is the servlet with a firstName parameter. In the jsp file, I need to check if my firstName parameter has a value or not. If the firstName parameter is set, I need to display some html in the jsp file. If it is not set, I need to display different html in the jsp file.

Servlet.java:

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

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>

What would be the best way to do this?

Update:

Here is a great tutorial I found on JSTL, in case anyone needs it: http://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

like image 807
Marta Avatar asked Nov 30 '12 03:11

Marta


2 Answers

<% if (session.getAttribute("firstName") == null) { %>
    <p> some content </p>
<% } else {%>
    <p> other content </p>
<% } %>
like image 83
Isaac Avatar answered Oct 12 '22 23:10

Isaac


I think best way to do it is use of jstl tags. Because for simple jsp application it might good idea to add all java code to html but more heavier application it is best practice to use minimum java code on html.(seperate view layer from logic) (read this for more https://stackoverflow.com/a/3180202/2940265)
For your expectation you can easily use code like bellow

<c:if test="${not empty firstName}">
    <%--If you want to print content from session--%>
    <p>${firstName}</p>

    <%--If you want to include html--%>
<%@include file="/your/path/to/include/file.jsp" %>

    <%--include only get wrong if you give the incorrect file path --%>
</c:if>
<c:if test="${empty firstName}">
    <p>Jaathi mcn Jaathi</p>
</c:if>

If you didn't included jstl correctly you will unable to get expected output. refer this for such incident https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/

like image 42
Menuka Ishan Avatar answered Oct 12 '22 23:10

Menuka Ishan