Published 13 Sep, 2022

Java - getSession().getAttribute("....") -> null

Category Java
Modified : Sep 29, 2022
18

I created a signIn servlet:

@WebServlet(
    name = "SignInServlet",
    description = "check email & pass",
    urlPatterns = {"/authorization_signin"}
    )
public class SignInServlet extends javax.servlet.http.HttpServlet {

public SignInServlet(){
}

protected void doPost(HttpServletRequest request,
                      HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    UserDataSet user = new UserDataSet();
    SignInModel modelSignIn = new SignInModel();


    user.setEmail(request.getParameter("email"));
    user.setPassword(request.getParameter("password"));

    user = modelSignIn.doSignIn(user);

    if (request.getSession().getAttribute("loggedUser") == null) {
        if (user != null) {
            request.getSession().setAttribute("loggedUser", user);             request.getRequestDispatcher("authorization.jsp").forward(request, response);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            request.setAttribute("errorMessage", "Email or password is incorrect");
            request.getRequestDispatcher("index.jsp").forward(request, response);
            response.setStatus(HttpServletResponse.SC_OK);
        }
    }

}

@Override
 protected void doGet(HttpServletRequest request,
                  HttpServletResponse response) throws ServletException, IOException{
    response.setContentType("text/html; charset=utf-8");
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}

When user is signed in, servlet redirects him to "authorization.jsp"

<body>
<%

if (request.getSession().getAttribute("loggedUser") != null){
    UserDataSet user = (UserDataSet) request.getSession().getAttribute("loggedUser");

    System.out.println("In author :" + request.getSession().getAttribute("loggedUser"));
%>
<h1> Hello <%= user.getFirstName() %> <%= user.getLastName() %>!</h1>
<h2>AUTORIZED!</h2>
 <a href="/authorization_logout">Log Out</a>
 <%
 }
else {
%>
 <h1>GO HOME</h1>
 <%
}
 %>
 </body>

Then browser shows this page and data for signed in user

If write into URL "localhost:8080" and go to "index.jsp", then again on "authorization.jsp"

Filter check session:

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
public void destroy() {
}



public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) req;
    HttpServletResponse httpResponse = (HttpServletResponse) resp;

    System.out.println("Enter filter");

    System.out.println("Filter session: " + httpRequest.getSession(false).getAttribute("loggedUser"));



    UserDataSet user = (UserDataSet) httpRequest.getSession(false).getAttribute("loggedUser");

    if (user != null) {
        System.out.println("CHAIN");
        chain.doFilter(req, resp);
    } else {
        httpResponse.sendRedirect("/");
        System.out.println("Not signin");
    }
}

public void init(FilterConfig config) throws ServletException {

}

}

And getSession().getAttribute("loggedUser") returns null Why?

Next text: If I signed in and servlet open "authorization.jsp", then try to go throw URL on any *.jsp where session will be checked and the result will be null

What's wrong?

Answers

There are 2 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Session, Java, Servlets, Jsp. These have been categorized in sections for a clear and precise explanation.

5

My friend had help me found answer for this question in some answers on stackoverflow

If you put something in the session with request.getSession().setAttribute you have to read it from the session, not the request. Try <%= session.getAttribute("test") %>

Link to answer


37

I used

  <%=  request.getParameter("loggedUser") %>

For some reason I saw [1] in java logs when I used request.getSession().getAttribute("loggedUser") , I also observed in the same code that request.getParameter works, at least when values are passed by query strings and the "unchecked or unsafe operations" disappears from the log . So seems to me that can be a solution for this question.

[1]

_index__jsp.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.