how to set session timeout for java web application
To set the session timeout for a Java web application, you can use the setMaxInactiveInterval
method of the HttpSession
object.
Here is an example code snippet that demonstrates how to set the session timeout to 30 minutes:
import javax.servlet.http.HttpSession; import java.util.concurrent.TimeUnit; HttpSession session = request.getSession(); // Get the current session session.setMaxInactiveInterval((int) TimeUnit.MINUTES.toSeconds(30)); // Set the session timeout to 30 minutesSoruce:www.theitroad.com
In this example, the getSession()
method is called on the HttpServletRequest
object to get the current session, and then the setMaxInactiveInterval()
method is called on the HttpSession
object to set the session timeout to 30 minutes. The setMaxInactiveInterval()
method takes an integer argument, which represents the number of seconds that the session should be inactive before it times out.
Note that the above code uses java.util.concurrent.TimeUnit
to convert minutes to seconds, but you can also directly specify the number of seconds. For example, to set the session timeout to 15 minutes, you can use:
session.setMaxInactiveInterval(15 * 60); // Set the session timeout to 15 minutes
You can add this code to the doGet()
or doPost()
method of a servlet, or to a filter that is applied to all requests.