I need to implement simple servlet user authentication (in Java Dynamic Web Project) but there are things that confuse me quite a bit.
Firstly, the servlet for some reason creates the cookie JSESSIONID
although I never ask it to. And moreover, I cannot change its value, if I do request.addCookie(new Cookie("JSESSIONID", session.getId()))
, it makes something like this:
Cookie: JSESSIONID=6B5B441038414B4381EDB7470018F90E; JSESSIONID=7890D45DF445635C49BDEB3CADA8AD99; .......
so, it duplicates the cookie.
Secondly, I'm not sure where to compare cookie and session's id, and where and how to create session correctly (i.e. request.getSession(true? / false? / nothing?);
)
I've read some documentation but still need help.
I have the servlet HomeServlet
which shoud redirect user to authentication
page if the user is not authenticated.
Here's how I do that (HomeServlet.java
):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getSession().getAttribute("user") != null) {
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
} else {
response.sendRedirect("authentication");
}
}
And I also have AuthServlet
which serves jsp page with authentication forms and validates users.
AuthServlet.java
:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("ACTION");
if ("login".equals(action)) {
String[] result = doSomeValidations();
if (result.size() > 0) { // show validation errors
request.setAttribute("errorLoginMessage", result);
request.setAttribute("email", email);
doGet(request, response);
} else { // authenticate user
request.getSession().setAttribute("user", userObject);
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
} else if ("signup".equals(action)) {
// ...........................
} else {
doGet(request, response);
}
}
So, could you help me with understanding that? How do I implement user authentication and keep the user logged in throughout the session?