This makes no sense. Forget the request.getSession(boolean)
. Just get the session by request.getSession()
and never worry about the nullness/validness.
If you want to pass data through session attributes, then just do in test1
:
request.getSession().setAttribute("test", "foo");
and in test2
(which is of course requested in the same session after test1
):
String test = (String) request.getSession().getAttribute("test"); // Returns "foo".
As to using the session to check the logged-in User
, just do something like in the login code:
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
} else {
// Show error?
}
and then in a Filter
which is mapped on a url-pattern
which represents the restricted area, just check if the User
is present or not:
if (((HttpServletRequest) request).getSession().getAttribute("user") != null) {
chain.doFilter(request, response); // Just continue.
} else {
((HttpServletResponse) response).sendRedirect("login"); // Not logged-in, redirect to login page.
}
and when you logout, you just remove the User
from the session:
request.getSession().removeAttribute("user");
// Or, more drastically:
request.getSession().invalidate();
Alternatively you can also take a look for declarative Container Managed Security with help of some simple entries in web.xml
and the server.xml
. This way you don't need to hassle with login/filter logic yourself.
See also:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…