Spring MVC Getting Started Guide (5): Data Binding-1

First, let's take a look at the annotations that bind data:

1.@RequestParam, bind a single request data, which can be the data in the URL, the data submitted by the form or the uploaded file; 
2.@PathVariable, bind the URL template variable value; 
3.@CookieValue, bind the cookie data; 
4 . .@RequestHeader, binds request header data; 
5.@ModelAttribute, binds data to Model; 
6.@SessionAttributes, binds data to Session; 
7.@RequestBody, is used to handle Content-Type other than application/x-www- Form-urlencoded encoded content, such as application/json, application/xml, etc.; 
8. @RequestPart, binds "multipart/data" data, and can convert items according to the data type;


In practical applications, what we usually need to get is the model object. Don't worry, we don't need to bind the data to variables and then assign values ​​to the model. We only need to add the model to the corresponding action parameter (there is no need to specify the binding data here. The annotation) Spring MVC will automatically convert the data and bind it to the model object, everything is as simple as that. The test is as follows:

Add an AccountModel class as the test model:

package com.ray.models;

/**
 * @author Ray
 * @date 2018/4/18 0018
 */
public class AccountModel {

    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Add 2 modelAutoBind actions in DataBindController corresponding to get and post requests respectively:

/**
 * @author Ray
 * @date 2018/4/18 0018
 * 2 modelAutoBind actions correspond to get and post requests respectively
 */
@Controller
public class DataBindController {

    @RequestMapping(value = "/modelautobind", method = RequestMethod.GET)
    public String modelAutoBind(HttpServletRequest request,Model model){
        model.addAttribute("accountmodel", new AccountModel());
        return "modelautobind";
    }

    @RequestMapping(value = "/modelautobind", method = RequestMethod.POST)
    public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
        model.addAttribute("accountmodel",accountModel);
        return "modelautobindresult";
    }
}

Add modelautobind.jsp and modelautobindresult.jsp 2 views in the views folder to submit data and display the submitted data:

modelautobind.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>title</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    <form:form modelAttribute="accountmodel" method="post">
        用户名:<form:input path="username"/><br>
        密码:<form:password path="password"/><br>
        <input type="submit" value="Submit">
    </form:form>
</body>
</html>

modelautobindresult.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">
    <title>title</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
</head>
<body>
    Username: ${accountmodel.username}<br>
    Password: ${accountmodel.password}
</body>
</html>

Run the test:


Enter Ray for the username and 123 for the password, and submit:


You can see that the result is displayed correctly, indicating that the automatic binding is successful.


Note:

1. Regarding the parameters of @RequestParam, this is a complete writing of @RequestParam @RequestParam(value="username", required=true, defaultValue="AAA").

value indicates the name of the parameter to be bound in the request;

required indicates whether this parameter must be present in the request. The default value is true. This is to return 404 if there is no parameter to be bound in the request;

defaultValue indicates the default value if the parameter value specified in the request is empty;

If the parameter to be bound is a value type, it must have a value, otherwise an exception will be thrown, and if it is a reference type, the default is null (except for Boolean, which defaults to false);

 

2. In the two actions just added, you can see that the return type is different from the previous one, and it has changed from ModelAndView to String. This is because Spring MVC provides Model, ModelMap, and Map so that we can directly add the model data needed to render the view. , you can directly specify the corresponding view name when returning. At the same time, Map is inherited from ModelMap, and Model and ModelMap are inherited from ExtendedModelMap.

 

3.在刚才添加的视图modelautobind.jsp中可以看到<form:form<form:input 等标签,这是Spring MVC提供的表单标签,借助于这些标签我们可以很方便的把模型数据绑定到表单上面(当然你也可以选择继续使用原生的HTML表单标签),要使用Spring MVC只要在视图中添加引用 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>即可,关于Spring MVC表单标签的具体内容会在以后的文章中作介绍。


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325534672&siteId=291194637