SpringMVC (5) Data Binding-2
In SpringMVC (4) Data Binding-1, we introduced how to bind data with @ RequestParam. Next we will look at the usage of several other data binding annotations.
1. @ PathVariable is used to bind the variable value of the URL template. We have introduced the usage in the springing rule of SpringMVC (3) URL request to Action. Here we will not repeat it here.
2. @ CookieValue is used to bind data in the Cookie. Next we will use the sessionId in the Cookie for testing:
Add cookiebind action in DataBindController. The Code is as follows:
//@CookieValue Test@RequestMapping(value="/cookiebind", method = {RequestMethod.GET})public String cookieBind(HttpServletRequest request, Model model, @CookieValue(value="JSESSIONID", defaultValue="") String jsessionId){ model.addAttribute("jsessionId", jsessionId); return "cookiebindresult";}
Add a cookiebindresult. jsp View to the views folder. The Code is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Insert title here ${jsessionId}
Run the test:
You can see that sessionId has been obtained.
Note: @ CookieValue and @ RequestParam have three parameters, which have the same meaning as the @ RequestParam parameter.
3. @ RequestHeader is used to bind data in the request header. We use @ RequestHeader to obtain the User-Agent for Demonstration:
Add requestheaderbind action in DataBindController. The Code is as follows:
//@RequestHeader Test@RequestMapping(value="/requestheaderbind", method = {RequestMethod.GET})public String requestHeaderBind(HttpServletRequest request, Model model, @RequestHeader(value="User-Agent", defaultValue="") String userAgent){ model.addAttribute("userAgent", userAgent); return "requestheaderbindresult";}
Add a requestheaderbindresult. jsp View to the views folder. The Code is as follows:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Insert title here ${userAgent}
Run the test:
You can see that the User-Agent has been obtained.
Note: @ RequestHeader and @ RequestParam have three parameters, which have the same meaning as the @ RequestParam parameter.
4. @ ModelAttribute bind data to the model. In series (4) modelAutoBind action, the code for adding the data submitted by the form to the Model is as follows:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){ model.addAttribute("accountmodel", accountModel); return "modelautobindresult";}
With the help of @ ModelAttribute, we can simply add data to the Model and modify the above Code:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") AccountModel accountModel){ return "modelautobindresult";}
Run the test:
We can see that the submitted data is successfully bound.
5. The data scope in the Model is at the Request level. That is to say, in a Request, the data of the Model of other Request requests cannot be obtained. However, we can use @ SessionAttributes to store data in the session to maintain data between multiple requests, so that we can implement requirements such as step-by-step submission form. Next we will look at how to bind data to the AccountModel in two steps:
Add the following on DataBindController:
@SessionAttributes(value = "sessionaccountmodel")
Add usernamebind and passwordbind actions in DataBindController. The Code is as follows:
// @ SessionAttributes Test @ ModelAttribute ("sessionaccountmodel") public AccountModel initAccountModel () {return new AccountModel () ;}@ RequestMapping (value = "/usernamebind", method = {RequestMethod. GET}) public String userNameBind (Model model, AccountModel accountModel) {model. addAttribute ("sessionaccountmodel", new AccountModel (); return "usernamebind" ;}@ RequestMapping (value = "/usernamebind", method = {RequestMethod. POST}) public String userNameBindPost (@ ModelAttribute ("sessionaccountmodel") AccountModel accountModel) {// redirect to password binding test return "redirect: passwordbind ";} @ RequestMapping (value = "/passwordbind", method = {RequestMethod. GET}) public String passwordBind (@ ModelAttribute ("sessionaccountmodel") AccountModel accountModel) {return "passwordbind" ;}@ RequestMapping (value = "/passwordbind", method = {RequestMethod. POST}) public String passwordBindPost (@ ModelAttribute ("sessionaccountmodel") AccountModel accountModel, SessionStatus status) {// destroy the status of the object stored in @ SessionAttributes. setComplete (); // display the binding result return "sessionmodelbindresult ";}
Because @ SessionAttributes is specified on the controller, the parameter for @ ModelAttribute ("xxx") annotation will directly find the object named "xxx" in @ SessionAttributes, if not found, call the @ ModelAttribute ("xxx") annotation method to return the object and save it to @ SessionAttributes (if not found and @ ModelAttribute ("xxx ") the annotation method will throw HttpSessionRequiredException ). After the execution, you can call SessionStatus. setComplete () to destroy the stored object in @ SessionAttributes (data in HttpSession is not cleared ).
Add the usernamebind. jsp, passwordbind. jsp, and sessionmodelbindresult. jsp views in the views folder as follows:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %><% @ Taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
Insert title here
User name:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %><% @ Taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %>
Insert title here
Password:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>
Insert title hereUsername: $ {sessionaccountmodel. username}
Password: $ {sessionaccountmodel. password}
Run the test:
We can see that we have successfully bound the data to the AccountModel in two steps.
Note:
@ SessionAttributes has two parameters: value and types. value indicates the name of the object to be bound and types indicates the type of the object to be bound, for example, @ SessionAttributes (value = "sessionaccountmodel", types = AccountModel. class) the relationship between the two is and needs to be met at the same time. You can also specify multiple values and types, for example, @ SessionAttributes (value = {"aa", "aa"}, types = {XXX. class, YYY. class }).
6. @ RequestBody: Call the appropriate MessageConvert to convert the content in a non-application/x-www-form-urlencoded request to a specified object. It is usually used with @ ResponseBody and @ ResponseBody. @ RequestBody: on the contrary, it converts the specified object to the appropriate content (if the request header is Accept: application/json, json data is returned) and returns. Here we use an ajax request for Demonstration:
Since Spring parses json by default with Jackson, we want to add the jackson-core-asl-1.9.13.jar and jackson-mapper-asl-1.9.13.jar packages here to our project.
Modify the AccountModel to inherit the Serializable interface, and add an empty Constructor (convert Jackson ).
Add requestBodyBindaction in DataBindController. The Code is as follows:
//@RequestBody Test@RequestMapping(value="/requestbodybind", method = {RequestMethod.GET})public String requestBodyBind(Model model){ model.addAttribute("accountmodel", new AccountModel()); return "requestbodybind";}@RequestMapping(value="/requestbodybind", method = {RequestMethod.POST})public @ResponseBody AccountModel requestBodyBind(@RequestBody AccountModel accountModel){ return accountModel;}
Add the requestbodybind. jsp view in the views folder as follows:
<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %><% @ Taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %><Script src = "// ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
Insert title here
User name:
Password:
<Script type = "text/javascript"> $ (function () {$ ("# submit "). click (function () {var postdata = '{"username": "' + $ ('# username '). val () + '"," password ":"' + $ ('# password '). val () + '"}'; $. ajax ({type: 'post', contentType: 'application/json', url: 'http: // localhost: 8080/SpringMVCLesson/databind/requestbodybind ', processData: false, dataType: 'json', data: postdata, success: function (data) {alert ('username: '+ data. username + '\ npassword:' + data. password) ;}, error: function () {alert ('error... ') ;}}) ;}); </script>
Run the test:
The result is correct and the conversion is successful.
7. @ RequestPart: binds the "multipart/form-data" type data. Supports javax. servlet. http. Part file upload and supports type conversion. For details, see the official documentation:
Http://docs.spring.io/spring-framework/docs/3.2.x/spring-framework-reference/htmlsingle/#new-in-3.1-mvc-requestpart