The
HttpSession session = request.getSession(true);
and
HttpSession session = request.getSession();
both creates a new session if there is none present.
My problem is that i want to invalidate() the session if its allready present and then create a new one.
I that possible ..i mean is there any way out to achieve this..??
How about this?
HttpSession session = request.getSession(false); // Will not create a new session.
if(session!=null)
{
session.invalidate();
}
session = request.getSession(true);
first kill your old session
session.invalidate();
and after that reopen it with
HttpSession session = request.getSession(true);
dont work?
First do a session.invalidate(); and if necessary then do a response.sendRedirect("url"); to an url where in you can just do request.getSession(); to get a new session.
Note that this approach is not guaranteed to work in a JSP file, simply because the response is in most cases already committed (so that the container cannot set the new value of the jsessionid cookie in the response header). You really need to do this in a Servlet or Filter.
That said, why exactly do you want to invalidate the session and then immediately get a new session all in the same request? This sounds like a workaround for a certain problem for which there may be better solutions.
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
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
i am using spring 3 (annotations) with jsf, and i know how to create a session and how to invalidate it afterwards...
so when i login and use the logout button at the end, then everthing works great. but the problem is, the session remains if i don't click at the logout button. if i now log in with a different user, then the old session data remains - cause the old session wasn't invalidated.
so how can i force the system to create a new session if the old session wasn't invalidated?
You should clear the session when the user logs in. This way, whether they've logged out or not, you're starting fresh:
#RequestMapping("login")
public String login(LoginForm form, HttpServletRequest request, HttpSession session) {
session.invalidate();
HttpSession newSession = request.getSession(); // create session
// log the user in
return "successPage";
}
Steve's answer is good. Just to add a bit more context, you should always invalidate and create a new session after a user authentication event as a best practice against session fixation attacks.
Another way to accomplish what you are looking to do is to use Spring Security. I'm not sure if you've considered it, but by default it will handle invalidating and generating new sessions upon each user login for you. Also, it has other features which you may or may not find useful. This link may be helpful: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/ns-config.html. Scroll to section "3.3.3/ Session Fixation Attack Protection" for relavent info to your question
To Create new session after logout check session.isNew() condition if session is old then call invalidate(). Redirect logout method to /login mapping. It checks session and it will creates new session when you call invalidate() method.
Logout Code:
#RequestMapping("/logout")
public String logout() {
return "redirect:/login";
}
Login Code:
#RequestMapping(value = "/login")
public String login(HttpServletRequest request, HttpSession session) {
/*
* create new session if session is not new
*/
if (!session.isNew()) {
session.invalidate();
}
return "login";
}
In my web application i neet to check session already exist or not.
i want to check this in my servlet and in jsp also.
is there any way to check this.
Thanks
You can test it with HttpServletRequest#getSession(boolean create) with create=false. It will return null if not created yet.
HttpSession session = request.getSession(false);
if (session == null) {
// Session is not created.
} else {
// Session is already created.
}
If you actually want to create the session anyway if it doesn't exist, then just grab it and test the freshness using HttpSession#isNew():
HttpSession session = request.getSession();
if (session.isNew()) {
// Session is freshly created during this request.
} else {
// Session was already created during a previous request.
}
That was how you would do it in a Servlet. In a JSP you can only test the freshness with help of JSTL and EL. You can grab the session by PageContext#getSession() and then just call isNew() on it.
<c:if test="${pageContext.session.new}">
<p>Session is freshly created during this request.</p>
</c:if>
or
<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p>
One way is to set a session id in the jsp and then check the same session id in the other jsp or servlet to check if it is alive or not.
HttpSession session = req.getSession();
session.getId();
I've a JSP/Servlet Web App that consist of more than one servlet (and some JSPs)
I need to create an new HttpSession whenever the users access servlet A, knowing that, servlet A is the home page (i.e. he access it as the first servlet/page in the application).
So far so good, I can write the following code at the start of the servlet A:
HttpSession session = request.getSession(false);
if (session == null) {
logger.debug("starting new session...");
session = request.getSession();
// other stuff here
}
But the problem is, if the user didn't close his browser (even if he closes the tab - in Firefox for instance - the session will still be open), so when he try to open my site again, the last session will be re-used (in the range of session timeout of course), and this I don't need. I need that whenever he accesses Servlet A, he gets a brand new HttpSession.
But unfortunately, he may access this servlet twice per session based on some scenario!
It seems to me that you should not be using session for this purpose. Perhaps you can add a parameter to request (i.e. transaction id) and pass it around trough all your related requests, so when user would close page the transaction id would be gone. Then you can store any data associated with given transaction id in the http session or elsewhere and could also clean it after some time.
The spring framework has an abstraction called bean scope, which seem like a good fit for your scenario, so you can create a custom scope for your transaction (or user's session) and store all the data in some bean scoped with such custom scope.
You should store some information (attribute) in the session that it's been used. And if it has been, invalidate
HttpSession session = request.getSession();
Object isOld = session.getAttribute( "isOld" );
if ( isOld != null )
{
session.invalidate( );
// Recreate session
session = request.getSession( );
}
session.setAttribute( "isOld", new Object( ) );