Issue
I'm trying to store a User object in session in Servlet1. In Servlet2 I'm trying to get the values from the same logged in session from Servlet1.
Servlet1:
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
String emailFromForm = request.getParameter("email").toLowerCase();
String passwordFromForm = request.getParameter("passWord");
try {
User userThatLogsIn = manager.getUser(emailFromForm);
String passwordFromDB = userThatLogsIn.getPassword();
if (passwordFromDB.equals(passwordFromForm)) {
request.getSession().setAttribute("TheLoggedInUser", userThatLogsIn);
response.sendRedirect("/Slit/welcome.jsp");
} else {
request.setAttribute("error", "Unknown login, try again");
response.sendRedirect("/Slit/LoginFailed.jsp");
}
} catch (NullPointerException nullPointer) {
System.err.println("NullPointerException: " + nullPointer.getMessage());
response.sendRedirect("/Slit/LoginFailed.jsp");
}
}
Servlet2: Im getting a nullpointer sessionaccept fnavn at Mypage.MyPageServlet.sessionAccept(MyPageServlet.java:40)
private void sessionAccept(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
session.setMaxInactiveInterval(30 * 60);
User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
String fnavn = loggedInUser.getfName();
String enavn = loggedInUser.getlName();
String epost = loggedInUser.getEmail();
request.getSession().setAttribute("messageJSP", "Velkommen" + epost);
response.sendRedirect("Innstillinger.jsp");
}
Solution
This line
User loggedInUser = (User) request.getAttribute("TheLoggedInUser");
has to replaced with
User loggedInUser = (User)
request.getSession().getAttribute("TheLoggedInUser");
Answered By - Arvind Katte