Search code examples
jspservletshttpsession

Access servlet declared HttpSession in jsp


If the username, password and location are correct in login servlet i am creating a HttpSession and get to the jsp page. Below is the code in servlet:

    HttpSession sessionsa = request.getSession(true);
    sessionsa.setAttribute("user",userName); //userName is a String variable
    sessionsa.setAttribute("location",location); //location in value place is a String variable

Now on jsp page I am not able to access the attributes. Code on jsp:

    sessionsa = request.getSession();
    String user = (String) sessionsa.getAttribute("user");
    String location = (String) sessionsa.getAttribute("location");

It states that cannot find symbol variable sessionsa in class SimplifiedJSPServlet. Please help. Have been googling it since 2 days.


Solution

  • Do like this,first make the session creation false in your jsp.

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" session="false"%>
    

    Then to get the session,

    <%
    HttpSession sessionsa = request.getSession(false);
    String user = (String) sessionsa.getAttribute("user");
    String location = (String) sessionsa.getAttribute("location");
    %>
    

    By this you will get the user and location from the session.Hope this will help you.