The session is bound to a specific domain and by default also the context path. If OtherServlet
runs at a different domain and/or context, then it'll get a completely different session.
If you'd like to share the session among different webapplication contexts on the same domain, then you need to configure the servletcontainer accordingly to set the cookie path to empty. In case of for example Tomcat you can do that by setting the emptySessionPath
attribute of the HTTP Connector to true
in the /conf/server.xml
file.
Update, after a recheck of your question, the Helper.loginUser(request)
approach in the JSP is not a good practice. You should be doing this in a Servlet class. By the way, that may after all also be the cause that the servletcontainer fails to set the session cookie because the response headers are already sent, but you should already have noticed a self-explaining IllegalStateException
in the server logs then.
To help you a bit further, here's a basic kickoff example of the correct way to login an user:
HTML form in JSP:
<form action="login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
</form>
doPost()
method of a Servlet which is mapped on url-pattern
of /login
:
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirect to home/succes page.
} else {
request.setAttribute("error", "Unknown username/password, try again"); // Set error message.
request.getRequestDispatcher("login.jsp").forward(request, response); // Redisplay login.jsp.
}