Not start discussion about sessions and the most frequent situations which occur in a process of development I want to underline some things. What is the HTTP session? What for it exist? I hope you know that HTTP is a stateless protocol, that’s mean that there is no permanent connection between a browser and server. And as the result server doesn’t know who is an initiator of a request, even if an application has just one user. The session is a tool for identifying of requests author. The previous sentence is rough enough, but it explains the main purpose of the sessions. Every user gets it own session with unique identifier when he visits site first time.
Get a session ID
You can access the session id in Spring MVC application in a same way as in Java EE application. You just need to pass HttpSession object in arguments of a RequestHandler method and then invoke appropriate method for the session object:
... @RequestMapping(value="/", method=RequestMethod.GET) public ModelAndView mainPage(HttpSession session) { ModelAndView mav = new ModelAndView("home"); String sid = session.getId(); mav.addObject("sid", sid); return mav; } ...
Get a session attribute
When you want to access some session attribute in a controller you can use the same construction like in the previous code snippet, but with a little changes:
... Object someObject = session.getAttribute("nameOfAttribute"); ...
If you definitely know what type of object will be returned you can specify an explicit cast.
Session attribute in JSP using JSTL
How to access session values in a JSP using JSTL after you put some value into the session in a controller?
@Controller @SessionAttributes("sValue") public class NavController { ... @RequestMapping(value="/", method=RequestMethod.GET) public ModelAndView mainPage() { ModelAndView mav = new ModelAndView("home"); String sValue = "Some value"; mav.addObject("sValue", sValue); return mav; } ...
The access to the sValue session attribute will look like:
... <p> ${sValue} </p> ...
Delete session
Deletion of a session is pretty simple, you just need to call an invalidate() method for a session object. After this action the session will be entirely removed for a particular user.
Session timeout
A session timeout defines a period of session’s life, during this time session is valid. The most simple way to define the session timeout in Java EE applications is to specify it in a web.xml file. Add the following code snippet in your application’s web.xml file to set the session timeout:
<session-config> <session-timeout>10</session-timeout> </session-config>
In the example above I have set a session timeout value equals to 10 minutes.
thx, ur article really help me :D