Home > Java > javaTutorial > body text

SpringMVC Learning Series (5) Data Binding-2

黄舟
Release: 2017-03-03 10:54:54
Original
1445 people have browsed it

In series (SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2) we introduced how to use @RequestParam to bind data. Let's take a look at how to use other data binding annotations.

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.@PathVariable is used to bind URL template variable values. We have already introduced how to use this in series (SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2) and will not go into details here.

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.@CookieValue is used to bind the data in Cookie. Below we use the sessionId in the cookie to do the test:

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";
}
Copy after login


Add a cookiebindresult in the views folder .jsp view, the code is as follows:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><meta><title>Insert title here</title>
    ${jsessionId}
Copy after login


Run the test:

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2

You can see that the sessionId has been obtained.

Note: @CookieValue also has SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 parameters like @RequestParam, and its meaning is the same as the @RequestParam parameter.

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.@RequestHeader is used to bind the data in the request header. We use @RequestHeader to get the User-Agent for demonstration:

Add requestheaderbind action to 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";
}
Copy after login


Add a requestheaderbindresult.jsp view in the views folder, the code is as follows:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><meta><title>Insert title here</title>
    ${userAgent}
Copy after login


Run the test:

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2

You can see that the User-Agent has been obtained.

Note: @RequestHeader also has SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 parameters like @RequestParam, and its meaning is the same as the @RequestParam parameter.

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.@ModelAttribute binds data to the model. In the modelAutoBind action of series (SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2), 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";
}
Copy after login

With the help of @ModelAttribute, we can more simply add the data to the In Model, modify the above code to:

@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") AccountModel accountModel){    
    return "modelautobindresult";
}
Copy after login

Run the test:

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2

You can see that the binding is still successful Submitted data.

SpringMVC Learning Series (5) Data Binding-2. The data scope in Model is Request level, which means that in one Request request, the data of the Model requested by other Request requests cannot be obtained. But we can use @SessionAttributes to store data in the session to maintain data between multiple requests, so that we can implement requirements such as submitting forms in steps. Let’s look at how to bind data to AccountModel in SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 steps:

在DataBindController上添加:

@SessionAttributes(value = "sessionaccountmodel")
Copy after login

在DataBindController添加usernamebind和passwordbind action,代码如下:

//@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){    
    //重定向到密码绑定测试
    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){    
    //销毁@SessionAttributes存储的对象    status.setComplete();    //显示绑定结果
    return "sessionmodelbindresult";
}
Copy after login


由于我们在controller上指定了@SessionAttributes,所以在@ModelAttribute(“xxx”)注解的参数会直接在@SessionAttributes中查找名为”xxx”的对象,如果没有找到则调用@ModelAttribute(“xxx”)注解的方法返回对象并存入@SessionAttributes(如果没有找到且没有@ModelAttribute(“xxx”)注解的方法就会抛出HttpSessionRequiredException)。当执行到最后一步就可以调用SessionStatus .setComplete()方法把@SessionAttributes中保存对象销毁了(不会清除HttpSession中的数据)。

在views文件夹中添加usernamebind.jsp、passwordbind.jsp和sessionmodelbindresult.jsp视图内容分别如下:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><meta><title>Insert title here</title>
    <form>     
        用户名:<input><br>
        <input>
    </form>  
Copy after login


nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><meta><title>Insert title here</title>
    <form>     
        密 码:<password></password><br>
        <input>
    </form>  
Copy after login


nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><meta><title>Insert title here</title>
    用户名:${sessionaccountmodel.username}<br>
    密 码:${sessionaccountmodel.password}
Copy after login


运行测试:

SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2

SpringMVC Learning Series (5) Data Binding-2

SpringMVC Learning Series (5) Data Binding-2

可以看到我们已经成功的分SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2步把数据绑定到AccountModel中了。

注:

@SessionAttributes有value和types两个参数其中value指明要对象的名称,types指定要绑定对象的类型,如@SessionAttributes(value = "sessionaccountmodel", types=AccountModel.class)两者是and关系,需要同时满足。也可以同时指定多个value和types 如:@SessionAttributes(value = {"aa", "aa"} , types={XXX.class, YYY.class}) 。

SpringMVC Learning Series (5) Data Binding-2.@RequestBody 调用合适的MessageConvert来把非application/x-www-form-urlencoded请求中的内容转换为指定的对象它通常与@ResponseBody合用,@ResponseBody与.@RequestBody刚好相反,他把指定的对象转换为合适的内容(请求头为Accept:application/json 则返回json数据)并返回。这里我们用一个ajax请求做演示:

由于Spring默认解析json用的是Jackson,所以我们这里要把jackson-core-asl-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.9.SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.jar和jackson-mapper-asl-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.9.SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.jar两个包添加到我们项目。

修改AccountModel让其继承Serializable接口,并添加一个空的构造函数(为了Jackson做转换)。

在DataBindController添加requestBodyBindaction,代码如下:

//@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;
}
Copy after login


在views文件夹中添加requestbodybind.jsp视图内容如下:

nbsp;html PUBLIC "-//WSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2C//DTD HTML SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.0SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2 Transitional//EN" "http://www.wSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.org/TR/htmlSpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2/loose.dtd"><script learning series data binding-2 binding-springmvc binding-2.8.springmvc></script><meta><title>Insert title here</title>
    <form>     
        用户名:<input><br>
        密 码:<password></password><br>
        <input>
    </form> 
    
    <script>
        $(function() { 
            $("#submit").click(function() {   
                var postdata = &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;{"username":"&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29; + $(&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;#username&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;).val() + &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;","password":"&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29; + $(&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;#password&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;).val() + &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;"}&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;;   
                $.ajax({  
                    type : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;POST&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;,  
                    contentType : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;application/json&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;,  
                    url : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;http://www.php.cn/:8080/SpringMVCLesson/databind/requestbodybind&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;,  
                    processData : false,  
                    dataType : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;json&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;,  
                    data : postdata,  
                    success : function(data) {  
                        alert(&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;username : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;+data.username+&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;\npassword : &#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;+data.password);  
                    },  
                    error : function() {  
                        alert(&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;error...&#SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-29;);  
                    }  
                }); 
            });
        });    </script> 
Copy after login


运行测试:

SpringMVC Learning Series (5) Data Binding-2

The result is correct, proving that the conversion is successful.

SpringMVC Learning Series (5) Data Binding-2.@RequestPart binds "multipart/form-data" type data, supports javax.servlet.http.Part file upload, and can perform type conversion. For details, see the official documentation:

http://docs.spring.io/spring-framework/docs/SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.x/spring-framework-reference/htmlsingle/#new-in-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2.SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2-mvc-requestpart

The above is the SpringMVC learning series (SpringMVC Learning Series (5) Data Binding-2) The content of Data Binding-SpringMVC Learning Series (SpringMVC Learning Series (5) Data Binding-2) Data Binding-2. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!