Session management is one of the essential parts for each web application. Since Spring MVC is a powerful framework for web development, it has its own tools and API for the interaction with sessions. Today I intend to show you the basic ways of session processing within Spring MVC application. That is: how to process forms, add objects into a session, and display objects from the session on JSP. I will try my best, so let’s start.
This Spring MVC Session tutorial will be based on one of the previous posts on my blog, related to the form handling. I’m going to extend the application by adding some session logic to the existing student-form, and create a new page with a form and a single text field on it. The text from the field will be processed by a controller and added to the session.
In order to check the session functionality I will display the session objects on the pages using JSTL. You can download the source in the end of the tutorial.
Form with a single text field
Firstly I need to create a view and a controller. I will start from the view creation and after that I’ll demonstrate the corresponding controller with the session logic.@Controller
@SessionAttributes("thought")
public class SingleFieldController {
@RequestMapping(value="/single-field")
public ModelAndView singleFieldPage() {
return new ModelAndView("single-field-page");
}
@RequestMapping(value="/remember")
public ModelAndView rememberThought(@RequestParam String thoughtParam) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("thought", thoughtParam);
modelAndView.setViewName("single-field-page");
return modelAndView;
}
}
The last thing I should to do is to add a link to the new page on the index.jsp:
On the screenshots below you can see the result of the code execution:
And the results:
And
Adding a custom object into the session
In this section I’m going to show you how to add a custom object into the session, and how to display еру object’s properties on JSP. The role of the custom object will play the Person object. Firstly I’ll modify the existing person controller:Comparing with the latest version I have added two new strings:
@SessionAttributes("personObj");
modelAndView.addObject("personObj", person);
The result of the code execution is following:
And
No comments:
Post a Comment