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

Let's take a look at how to use several other data binding annotations.

1. @CookieValue is used to bind the data in the cookie. Let's test by getting the sessionId in the cookie:

Add the cookiebind action to the DataBindController, the code is as follows:

/**
     * @CookieValue is used to bind the data in the cookie
     */
    @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 in the views folder with the following code:

<%@ 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>
${jsessionId}
</body>
</html>
Run the test:


You can see that the sessionId has been obtained.

Note: A brief description of JSESSIONID

Note: @CookieValue has 3 parameters like @RequestParam, and its meaning is the same as that of @RequestParam.


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 in DataBindController, the code is as follows:

/**
     * @RequestHeader is used to bind the data in the request header
     */
    @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 in the views folder with the following code:

<%@ 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>
    ${userAgent}
</body>
</html>

Run the test:


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

Note: @RequestHeader has the same three parameters as @RequestParam, and its meaning is the same as that of @RequestParam parameter.


3. @ModelAttribute binds data to the model. In the modelAutoBind action of series (4), 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 to:

/**
     * @ModelAttribute binds data to the model
     */
    @RequestMapping(value = "/modelautobind", method = RequestMethod.POST)
    public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") AccountModel accountModel){
        return "modelautobindresult";
    }

Run the test:


You can see that the submitted data is still successfully bound.


4. The data scope in the Model is at the Request level, that is to say, in a Request request, the data of the Model requested by other Requests cannot be obtained. But we can use @SessionAttributes to store data in the session to keep data between multiple requests, so that we can achieve requirements such as submitting forms in steps. Let's see how to bind data to AccountModel in 2 steps:

On the DataBindController class add:

@SessionAttributes(value = "sessionaccountmodel")

Add usernamebind and passwordbind to DataBindController, the code is as follows:

/**
     * @SessionAttributes stores data in session to keep data between multiple requests
     */
    @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 "sessionmodelbingresult";
    }

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

在views文件夹中添加usernamebind.jsp、passwordbind.jsp和sessionmodelbindresult.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>Insert title here</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="sessionaccountmodel" method="post">
        用户名:<form:input path="username"/><br>
        <input type="submit" value="Submit">
    </form:form>
</body>
</html>
<%@ 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>Insert title here</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="sessionaccountmodel" method="post">
        密码:<form:password path="password"/><br>
        <input type="submit" value="Submit">
    </form:form>
</body>
</html>
<%@ 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>Insert title here</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>
    用户名:${sessionaccountmodel.username}<br>
    密码:${sessionaccountmodel.password}
</body>
</html>

运行测试:




可以看到我们已经成功的分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}) 。


Guess you like

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