I'm developing Java Servlets. At the point of checking whether a user is logged in, I want to check if the HTTP request has a valid session. For checking that, I have 2 possibilities:
(1)
protected void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
// user is logged in
...
}
}
Since I pass false as an argument, there is no new session created if there is no valid session existing already, and the function returns null, for what I can check.
Or I do:
(2)
if (request.isRequestedSessionIdValid()) {
// user is logged in
...
}
Is there any difference, any advantage/disadvantage? Or do both functions do more or less the same?
Form Javadoc
isRequestedSessionIdValid
boolean isRequestedSessionIdValid()
Checks whether the requested session ID is still valid.
If the client did not specify any session ID, this method returns false.
Returns:
true if this request has an id for a valid session in the current session context; false otherwise
So in sense both are same. But what you need to be aware of is request.getSession(false) will be null only in case of first request to the container. After the first request container creates a session and sends Jsessionid cookie along with response , so that it can track subsequent requests from the same browser. So in your case instead of checking if session is null or not, you should store a session attribute "is_logged_in"=true and check for this attribute as well if session is not null.
Based on the wording of the JavaDoc, it seems like there would be a distinction: if a valid session has already been created (from a prior call to request.getSession(true)), then the requested session ID will not be valid, but request.getSession(false) will have a valid (non-null) session to return. I haven't tested this theory.
Related
Here request is an object type which extends HttpServletRequest. This is the sequence of code.
HttpSession session;
session = request.getSession(false);
response.sendRedirect(redirect);
session = request.getSession(false);
In the first line, able to get the valid session value. But after 2nd statement sendRedirect execution. session object is becoming NULL in the 3rd statement.
For the redirected request to come back and attach to the same session, it needs a session ID, usually carried in a JSESSIONID (or another name) cookie or in the URL as a parameter.
This cookie or URL parameter should be added by the servlet container and you should not have to add it yourself.
If you do not see the cookie in your browser, and you are not attaching the JSESSIONID to the URL, then it is creating a new session with each request, and not attaching to the same session
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?
Firstly, the servlet for some reason creates the cookie JSESSIONID
although I never ask it to
HttpSession jsession = request.getSession();
you are requesting a session here and JSESSIONID cookie is created by the container in response
how to create session correctly request.getSession(true? / false? / nothing?);
request.getSession() and request.getSession(true) are exactly the same they start a new session if needed ,but request.getSession(false) means if there is already a session use it but if there isn't don't start one.
How and where you want to start the session is dependent entirely on your requirements
response.addCookie(new Cookie("JSESSIONID", jsession.getId()));
you are not suppossed to add a JSESSIONID cookie yourself , the container will do it for you .
Also you should create session once in your app , once the JSESSIONID cookie is stored in the user's browser(provided cookies are enabled) ,it will be sent along with the request.
How do I implement user authentication
Highly subjective and depends on requirements , you can read this https://docs.oracle.com/cd/E19226-01/820-7627/bncby/index.html
keep the user logged in throughout the session
Your session cookies will help you with that once the user has been authenticated ,as an example login to facebook and keep your cookies tab open
I noticed that the jsessionId will get sent across to the server so in the filter I could actually get the expired session id from the cookies.
Is it ok to put a filter logic like the following?
Cookie jsessionCookie = getSessionIdCookies(request);
Session session = request.getSession(false);
if (session == null || !(jsessionCookie.getValue().equals(session.getId())) {
//this should be a timeout handling
....
} else {
// normal moving forward
}
Since the session == null could also because of a new request (which can be filtered out by setting particular filter rules), can I more rely on !(jsessionCookie.getValue().equals(session.getId())?
Or even change the request.getSession(false) to request.getSession() and just always compare the cookie with the session id?
Is there a better management practice for session timeout management?
You can register a HttpSessionListener on the ServletContext to get notified when a session is invalidated.
General question about java servlets and the best way to handle requests. If I hit my doGet method from a remote server request:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
....
<do work here>
....
kill(request);
}
private void kill(HttpServletRequest request) {
//How do I kill the user session here?
}
After I process the request at my end and generate my output to the requester, I want to basically "kill" their session. Currently, that session lingers and thus eats up memory. Then once the max is reached, all other calls are timed out.
I tried creating a HttpSession object using the request object, but got the same results:
HttpSession session = request.getSession();
session.invalidate();
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
is the proper way to go as suggested by the documentation. A new session will be created once the client sends a new request.
You mentioned that your sessions still take up memory. Do you have any other references to those objects on the session?
You also might want to have a look at: Servlet Session behavior and Session.invalidate
you can remove an attribute from a session using
session.removeAttribute("attribute name");
Try with
session = request.getSession(false); // so if no session is active no session is created
if (session != null)
session.setMaxInactiveInterval(1); // so it expires immediatly
If you dont want Session behavior i.e, having state between multiple requests. Why do you want to create/use session at all. Do not create session or do not store anything in the session.
To make sure that your code is not using session, write a request wrapper which will override getSession() methods.
Set a time-out period in web.xml
Hi just want to confirm when a session is expired in a webapp based on servlet.
The following session id will be available until the session is garbage collected, is that correct?
httpServletRequest.getRequestedSessionId()
Thanks,
C
if the session got expired, then at that point the session will be garbage collected and
httpServletRequest.getRequestedSessionId() will return new value when that method is called.
please check below url
http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.1/api/javax.servlet.http.HttpServletRequest.html#getRequestedSessionId%28%29
When a session is expired getRequestedSessionId() return id new session which will be created when you call this method
To check if session is timed-out (in invalid state) check isRequestedSessionIdValid
From JavaDoc
getRequestedSessionId
public abstract String
getRequestedSessionId()
Gets the session id specified with this request. This may differ from the
actual session id. For example, if the
request specified an id for an invalid
session, then this will get a new
session with a new id.
Returns:
the session id specified by this request, or null if the request
did not specify a session id