user1407668
user1407668

Reputation: 617

session().getAttribute is returning null

I have a servlet which calls a jsp page. In the servlet I am retrieving the username provided at the login correctly. But after setting the same in session, when i access the called jsp page, its returning null.

Servlet Code:

public class AdminServlet extends HttpServlet {
/**
 * 
 */
private static final long serialVersionUID = -4244742541587179390L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userName =  request.getParameter("name");
    System.out.println("UserName: " + userName); // Here it prints the username properly
    request.getSession(true).setAttribute(request.getParameter("name"), userName );
    RequestDispatcher rd = request.getRequestDispatcher("upload.jsp");
    rd.forward(request, response);
//  response.sendRedirect("upload.jsp");
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request,response);
}
}

JSP Code snippet where I am accessing this:

<label class="message">Welcome <%= session.getAttribute("userName") %></label>

What am I doing wrong here? Can anyone help please

Upvotes: 1

Views: 18567

Answers (4)

user2067687
user2067687

Reputation:

Just had a quick look I think this might be a little similar and might help: JSP Session.getAttribute() value return null

Upvotes: 0

Verdi
Verdi

Reputation: 84

I think you inverted the two params. It should be like this:

   request.getSession(true).setAttribute("userName", userName );

Upvotes: 1

nano_nano
nano_nano

Reputation: 12523

this is wrong:

request.getSession(true).setAttribute(request.getParameter("name"), userName ); 

I think it should be

request.getSession(true).setAttribute("userName", userName );

Upvotes: 1

Nimesh
Nimesh

Reputation: 802

you should get session value from the value of

request.getParameter("name");

or in servlet you need as follow:

request.getSession(true).setAttribute("userName",request.getParameter("name") );

Upvotes: 0

Related Questions