Search code examples
httpjspsessionjspx

How can i access session in different jspx?


I'm new to jspx and I'm not sure how I would do this. I have created a model-view-controller and have created a session in controller. Once the user has logged in, it creates the session.

HttpSession session = request.getSession();
session.setAttribute("user", username);

How can I access and display the username in the welcome.jspx page, so it would say

hello username

Solution

  • Use EL to access it.

    hello ${user}
    

    To prevent XSS attacks by username, show it using JSTL <c:out> so that XML special characters are escaped:

    <jsp:root xmlns:c="http://java.sun.com/jsp/jstl/core" ...>
    ...
    
    hello <c:out value="${user}" />