Search code examples
javajspjsp-tags

How to retrieve from session object in JSP?


I have a User Object which contains details like Name, Contact Details etc & I am storing this object in a session attribute. How do I save the name and contact details in a String variable in JSP Scriplet?

I tried using

String uname1 = (String) request.getSession().getAttribute(${requestScope['users'].getName()});

and many other combinations But it fails

My JAVA code

user = userDetails.getByUsername(username);

request.getSession().setAttribute("uname", user);

and in JSP I have

<%

String uname = (String) request.getSession().getAttribute("uname");
if (uname != null) {
response.sendRedirect("home.jsp");
}

%>

How Do I extract "name" from "uname" object and store it into a variable to be used for checking null value ?


Solution

  • you could store only the name in the session instead of the User object

    user = userDetails.getByUsername(username);
    
    request.getSession().setAttribute("uname", user.getName());
    

    because i see that in the jsp you are expecting a String object, if you want to store a User object than you should expect a User object instead of a string in the jsp

    user = userDetails.getByUsername(username);
    
    request.getSession().setAttribute("uname", user);
    
    <%
    
    User user = (User) request.getSession().getAttribute("uname");
    if (user.getName() != null) {
    response.sendRedirect("home.jsp");
    }
    
    %>