SpringMVC(十二):SpringMVC 处理输出模型数据之@ModelAttribute

Spring MVC提供了以下几种途径输出模型数据:
1)ModelAndView:处理方法返回值类型为ModelAndView时,方法体即可通过该对象添加模型数据;
2)Map及Model:处理方法入参为org.springframework.ui.Model、org.springframework.ui.ModelMap或java.util.Map时,处理方法返回时,Map中的数据会自动被添加到模型中;
3)@SessionAttributes:将模型中的某个属性暂存到HttpSeession中,以便多个请求之间可以共享这个属性;
4)@ModelAttribute:方法入参标注该注解后,入参的对象就会放到数据模型中。

在SpringMVC的hanlder类中用@ModelAttribute标注的方法,会在该handler内所有目标(action)方法执行之前被SpringMVC调用。

用法示例:

Account.java

 1 package com.dx.springlearn.entities;
 2 
 3 public class Account {
 4     public Integer id;
 5     private String username;
 6     private String password;
 7     private String registerDate;
 8     private String registerIP;
 9 
10     public Account() {
11     }
12 
13     public Account(Integer id, String username, String password, String registerDate, String registerIP) {
14         super();
15         this.id = id;
16         this.username = username;
17         this.password = password;
18         this.registerDate = registerDate;
19         this.registerIP = registerIP;
20     }
21 
22     public Account(String username, String password, String registerDate, String registerIP) {
23         super();
24         this.username = username;
25         this.password = password;
26         this.registerDate = registerDate;
27         this.registerIP = registerIP;
28     }
29 
30     public Integer getId() {
31         return id;
32     }
33 
34     public void setId(Integer id) {
35         this.id = id;
36     }
37 
38     public String getUsername() {
39         return username;
40     }
41 
42     public void setUsername(String username) {
43         this.username = username;
44     }
45 
46     public String getPassword() {
47         return password;
48     }
49 
50     public void setPassword(String password) {
51         this.password = password;
52     }
53 
54     public String getRegisterDate() {
55         return registerDate;
56     }
57 
58     public void setRegisterDate(String registerDate) {
59         this.registerDate = registerDate;
60     }
61 
62     public String getRegisterIP() {
63         return registerIP;
64     }
65 
66     public void setRegisterIP(String registerIP) {
67         this.registerIP = registerIP;
68     }
69 
70     @Override
71     public String toString() {
72         return "Account [id=" + id + ", username=" + username + ", password=" + password + ", registerDate="
73                 + registerDate + ", registerIP=" + registerIP + "]";
74     }
75 
76     
77 }
View Code

Handler类TestModelData.java

 1 package com.dx.springlearn.hanlders;
 2 
 3 import java.text.SimpleDateFormat;
 4 import java.util.Date;
 5 import java.util.Map;
 6 
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.web.bind.annotation.ModelAttribute;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.RequestParam;
11 import org.springframework.web.servlet.ModelAndView;
12 
13 import com.dx.springlearn.entities.Account;
14 
15 @Controller
16 public class TestModelData {
17     private final String SUCCESS = "success";
18 
19     @ModelAttribute
20     public void getAccount(@RequestParam(name = "id", required = false) Integer id, Map<String, Object> map) {
21         if (id != null) {
22             System.out.println("read account(id=" + id + ") from db");
23             Account account = new Account(1, "tommy", "123456", "2018-01-20 21:56:09", "127.0.0.1");
24             map.put("account", account);
25         } else {
26             System.out.println("the acount id is null");
27         }
28     }
29 
30     @RequestMapping("/testModelAttribute")
31     public ModelAndView testModelAttribute(Account account) {
32         System.out.println("accept account:" + account);
33         String viewName = SUCCESS;
34         ModelAndView modelAndView = new ModelAndView(viewName);
35         modelAndView.addObject("currentTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
36 
37         return modelAndView;
38     }
39 }

测试表单页面:

    <form id="form_testModelAttribute" action="testModelAttribute"
        method="POST">
        <input name="id" type="hidden" value="1"/>
        username:<input name="username" type="text" value="tommy" /><br>
        <!-- password:<input name="password" type="password" /><br> -->
        register date:<input name="registerDate" type="text" value="2018-01-20 21:56:09" /><br>
        register ip:<input name="registerIP" type="text" value="127.0.0.1"/><br>
        <input type="submit" value="Submit"/>
    </form>

除了handler目标方法参数第一个参数名称与存放到map中的对象名称一致外,也可以使用@ModelAttribute标注handler目标方法参数:

package com.dx.springlearn.hanlders;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dx.springlearn.entities.Account;

@Controller
public class TestModelData {
    private final String SUCCESS = "success";

    @ModelAttribute
    public void getAccount(@RequestParam(name = "id", required = false) Integer id, Map<String, Object> map) {
        if (id != null) {
            System.out.println("read account(id=" + id + ") from db");
            Account account = new Account(1, "tommy", "123456", "2018-01-20 21:56:09", "127.0.0.1");
            map.put("testabc", account);
        } else {
            System.out.println("the acount id is null");
        }
    }

    @RequestMapping("/testModelAttribute")
    public ModelAndView testModelAttribute(@ModelAttribute("testabc") Account account) {
        System.out.println("accept account:" + account);
        String viewName = SUCCESS;
        ModelAndView modelAndView = new ModelAndView(viewName);
        modelAndView.addObject("currentTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        return modelAndView;
    }
}

运行流程:

1)运行有@ModelAttribute注解标注的方法:从数据库中取出对象,把对象放入到Map中,键值为:user;

2)SpringMVC从Map中取出User对象,并把表单的请求参数赋值给该User对象的对应属性;

3)SpringMVC把上述对象传入目标方法的参数(参数名称必须与Map中的键值一致)。

注意:在@ModelAttribute修饰的方法中,放入Map是的键类型要与目标方法入参类型一直,而且Map是的键名称要与目标方法入参的参数名一致。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值