Is there a way to "catch" the session timeout event, so as to retrieve data from HttpSession before its invalidated ?
We're implementing the Filter Interface, and in the doFilter method, the user we stored in the session object at login is null when session times out.
Thanks in advance.
You should be able to register an HttpSessionListener for your webapp that will allow you to get notified when a Session is destroyed.
It has two callback methods:
public void sessionCreated(HttpSessionEvent se)
public void sessionDestroyed(HttpSessionEvent se)
The HttpSessionEvent class has a getSession method that should let you get the affected session.
The listener class is registered in the web.xml
<listener>
<description>My Session Listener</description>
<listener-class>
my.package.MySessionListener
</listener-class>
</listener>
Have the user object implement HttpSessionBindingListener, then it can see for itself when it is added to or removed from the session.
You can always ad a piece of JSP that will check to see if your session is still active or valid - basically check to see if a session var exists (!=null) and if it doesn't - redirect the user to another page -
<%
// check for session object
HttpSession validuser = request.getSession();
// check to see if session var exists
if (validuser.getValue("auth_user") == null) {
response.sendRedirect("admin3.jsp?access+denied");
}
// if the session var is null then redirect the user
Hope this helps
Mark
Source : http://www.coderanch.com/t/279538/JSP/java/jsp-session-timeout
Related
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.
If I am mentioning the session timeout in descriptor page
<session-config>
<session-timeout>30</session-timeout>
</session-config>
Before terminating session I want to do insert operation in database. Is there any possibility for insertion. I have a thought that when user logins the page and I can use trigger to insert the data for 30 minutes. But if anyone else changes to -1 or more than 30 mins without noticing the trigger is running when user logins at that case what can I do for it?
The remaining time for a session timeout changes every time the client makes interaction, so timing this for 30 minutes is a wrong solution.
Instead use an HttpSessionListener. A registered HttpSessionListener is called every time an HTTP session is created or destoryed (invalidated). This does not depend on the configured session timeout. The sessionDestroyed() method is always called right before a session is invalidated and discarded.
public class MySessionListener implements HttpSessionListener {
#Override
public void sessionCreated(HttpSessionEvent se) {}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
// Here session is destoryed.
// You can insert data to your database here.
// You can access the session like this:
HttpSession sess = se.getSession();
}
}
Here is how you can register your HttpSessionListener it in your web.xml:
<web-app>
<listener>
<listener-class>com.dummy.MySessionListener</listener-class>
</listener>
</web-app>
I want to create a global session in JSP to be used in all Servlets and JSP files as is done in PHP with the instruction:
<?php
session_start ();
?>
Tried with:
HttpSession s = request.getSession ();
and set. It works, but I have to make several passes from one class to another to have it in another JSP file.
How can I do?
You can use ServletContext Listener to maintain the variables for all your application Listener to
ServletContext, so you can execute some code when the application starts (is deployed correctly) to
initialize the attributes on the ServletContext) and when it finish (before its undeployed).
public final class MyAppListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
System.out.println("Application gets started.");
ServletContext servletContext = event..getServletContext();
servletContext.setAttribute("someAttribute", "Hello world!");
}
public void contextDestroyed(ServletContextEvent event) {
System.out.println("Application has finished.");
}
}
If you're using Java EE 5, you should configure the listener in the web.xml
<listener>
<listener-class>mypackage.listener.MyAppListener</listener-class>
</listener>
request.getSession() will create a session the first time it is called, subsequent getSession() calls will use the same session as long as the session id is available on the URL (or a cookie).
You need to make sure to call response.encodeUrl(...) when generating links from one page to another so that the session ID is included in the URL.
eg: www.mysite.com/somePage;JSESSIONID=adfasdfasdfasdf
From tutorialspoint
By default, JSPs have session tracking enabled and a new HttpSession
object is instantiated for each new client automatically. Disabling
session tracking requires explicitly turning it off by setting the
page directive session attribute to false as follows:
<%# page session="false" %>
You would then use session.setAttribute(name, value) in your servlets to store session variables and ${name} (or equivalently <% out.print(session.getAttribute(name)); %>) to retrieve and output them in your JSPs.
Try with
ServletContext servletContext = event..getServletContext();
then servletContext.getSession(). I think it should work.You need one scope who dies till the end of Application and getSession from that scope.
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";
}