Spring MVC 数据绑定

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring MVC 数据绑定相关的知识,希望对你有一定的参考价值。

 
 
Spring支持多种形式的类型绑定,包括:
1、基本数据类型、String和String[]
2、简单对象类型
3、List类型
4、Set类型
5、Map类型
6、复合数据类型
 
 
接下来一个一个的实现:
1、基本数据类型、String和String[]。
请求处理方法:

public void registBean(String username,int age,double income,String[] interests,boolean marrid)

保证JSP页面上提交项和方法中对应参数同名。其中boolean的提交项的value是字符串true和false。

 

2、简单对象类型
请求处理方法:

public void registBean(UserBean2 user)

需要保证JSP页面上提交项和UserBean对象中的属性同名即可。
 
 
3、List类型
List需要绑定在Bean对象上,直接写在请求处理方法中作为参数是不行的,更重要的一点是要创建对象(ArrayList).

public class UserBean2{ 

    private List<AddressListBean> list= new ArrayList<AddressListBean>(); 

}

请求处理方法:

public void registBean(UserBean2 user)

 JSP页面上提交项的命名:参数名[下标].属性名。

 

4、 Set类型
与List方法类似,但是必须先在Set对象中Add相应的数量的模型对象.

public class UserBean2{ 

    private Set<AddressSetBean> set= new HashSet<AddressSetBean>(); 

    public Classes(){

      set.add(new AddressSetBean());

      set.add(new AddressSetBean());

      set.add(newAddressSetBean());

    }

}

 

5、Map对象
Map也需要绑定在Bean对象上。

public class UserBean2{ 

    private Map<String String> map= new HashMap<String String>(); 

}

请求处理方法:

public void  registBean(UserBean2 user)

JSP页面上的提交项命名:参数名[‘键名’]
 
 
6、复合数据类型
所谓复合数据类型,指代自定义Bean中某个属性又是一个自定义Bean.

public class UserBean2{

  private String name;

  private int age;

  private AddressBean address;

}

请求处理方法:

public void registBean(UserBean2 user)

JSP页面提交项命名:复合属性名.属性名

 

主要代码:

  

 1 package com.cy.springannotation.entity;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.HashSet;
 6 import java.util.List;
 7 import java.util.Map;
 8 import java.util.Set;
 9 
10 
11 public class UserBean2 {
12     private String username;
13     private int age;
14     private double income;
15     private String[] interests;
16     private boolean married;
17     //List不能单独使用,必须要绑定到某一个具体的Bean,并且要实例化ArrayList
18     private List<AddressListBean> list=new ArrayList<AddressListBean>();
19     //Set不能单独使用,必须要绑定到某一个具体的Bean,并且要实例化HashSet
20     private Set<AddressSetBean> set=new HashSet<AddressSetBean>();
21     //Map不能单独使用,必须要绑定到某一个具体的Bean,并且要实例化HashMap
22     private Map<String,AddressMapBean> map=new HashMap<String,AddressMapBean>();
23     //复合数据类型
24     private AddressBean address;
25     
26     public UserBean2(){
27         //set集合需要提前定义个数
28         for(int i=0;i<2;i++){
29             AddressSetBean asb=new AddressSetBean();
30             set.add(asb);
31         }
32         
33     }
34     public String getUsername() {
35         return username;
36     }
37     public void setUsername(String username) {
38         this.username = username;
39     }
40     public int getAge() {
41         return age;
42     }
43     public void setAge(int age) {
44         this.age = age;
45     }
46     public double getIncome() {
47         return income;
48     }
49     public void setIncome(double income) {
50         this.income = income;
51     }
52     public String[] getInterests() {
53         return interests;
54     }
55     public void setInterests(String[] interests) {
56         this.interests = interests;
57     }
58     public boolean isMarried() {
59         return married;
60     }
61     public void setMarried(boolean married) {
62         this.married = married;
63     }
64     
65         public Map<String, AddressMapBean> getMap() {
66         return map;
67     }
68     public void setMap(Map<String, AddressMapBean> map) {
69         this.map = map;
70     }
71     
72     public Set<AddressSetBean> getSet() {
73         return set;
74     }
75     public void setSet(Set<AddressSetBean> set) {
76         this.set = set;
77     }
78     public List<AddressListBean> getList() {
79         return list;
80     }
81     public void setList(List<AddressListBean> list) {
82         this.list = list;
83     }
84     public AddressBean getAddress() {
85         return address;
86     }
87     public void setAddress(AddressBean address) {
88         this.address = address;
89     }
90 
91 }

 

 

 

  页面设置“

  

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>注册页面</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26   <form action="regist.do" method="post">
27     <table>
28        <tr>
29            <td>用户名:</td>
30            <td><input type="text" name="username"/></td>
31        </tr>
32        <tr>
33            <td>年龄:</td>
34            <td><input type="text" name="age"/></td>
35        </tr>
36         <tr>
37            <td>收入:</td>
38            <td><input type="text" name="income"/></td>
39        </tr>
40         <tr>
41            <td>兴趣:</td>
42            <td><input type="checkbox" name="interests" value="看书"/>看书
43                <input type="checkbox" name="interests" value="上网"/>上网
44                <input type="checkbox" name="interests" value="唱歌"/>唱歌
45                <input type="checkbox" name="interests" value="运动"/>运动
46                <input type="checkbox" name="interests" value="散步"/>散步
47            </td>
48        </tr>
49        <tr>
50            <td>是否结婚:</td>
51            <td><input type="radio" name="married" value="true" checked="checked"/>52                <input type="radio" name="married" value="false" />53            </td>
54        </tr>
55        <tr>
56                 <td>list地址1:</td>
57                 <td><input type="text" name="list[0].addressListName"/></td>
58             </tr>
59             <tr>
60                 <td>list地址2:</td>
61                 <td><input type="text" name="list[1].addressListName"/></td>
62             </tr>
63             
64              <tr>
65                 <td>set地址1:</td>
66                 <td><input type="text" name="set[0].addressSetName"/></td>
67             </tr>
68             <tr>
69                 <td>set地址2:</td>
70                 <td><input type="text" name="set[1].addressSetName"/></td>
71             </tr> 
72             <tr>
73                 <td>map地址1:</td>
74                 <td><input type="text" name="map[‘a0‘].addressMapName"/></td>
75             </tr>
76             <tr>
77                 <td>map地址2:</td>
78                 <td><input type="text" name="map[‘a1‘].addressMapName"/></td>
79             </tr>
80             <tr>
81                 <td>地址:</td>
82                 <td><input type="text" name="address.addressName"/></td>
83             </tr>
84        <tr>
85            <td colspan="2"> <input type="submit" value="注册"/> </td>
86        </tr>
87     </table>
88   </form>
89   </body>
90 </html>

 

业务控制器:

 

 1 package com.cy.springannotation.controller;
 2 
 3 import org.apache.log4j.Logger;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 
 7 import com.cy.springannotation.entity.AddressListBean;
 8 import com.cy.springannotation.entity.AddressSetBean;
 9 import com.cy.springannotation.entity.UserBean2;
10 
11 @Controller
12 public class RegistController {
13     private Logger log = Logger.getLogger(this.getClass());
14     
15     
16     /*    @RequestMapping("/regist.do")
17     public String regist(String username,int age,double income,String[] interests,boolean married){
18         log.info("username="+username);
19         log.info("age="+age);
20         log.info("income="+income);
21         log.info("interests="+interests.length);
22         log.info("married="+married);
23         for (String string : interests) {
24             log.info("兴趣有:"+string);
25         }
26         return "index";
27         
28     }
29 */    
30     //简单对象类型
31     @RequestMapping("/regist.do")
32     public String registBean(UserBean2 user){
33         log.info("username:"+user.getUsername());
34         log.info("age:"+user.getAge());
35         log.info("income:"+user.getIncome());
36         log.info("interests.length:"+user.getInterests().length);
37         log.info("married:"+user.isMarried());
38         log.info("addressList.size():"+user.getList().size());
39         log.info("addressSet.size():"+user.getSet().size());
40         log.info("addressMap.size():"+user.getMap().size());
41         log.info("address:"+user.getAddress().getAddressName());
42         
43        for (String string : user.getInterests()) {
44             log.info("具体的兴趣有=========" + string);
45         }
46        
47        for(AddressListBean add:user.getList()){
48            log.info("具体的list地址有=========" + add.getAddressListName());
49        }
50        
51        for(AddressSetBean asetb:user.getSet()){
52            log.info("具体的set地址有=========" + asetb.getAddressSetName());
53        }
54        
55        for(int i=0;i<2;i++){
56            log.info("具体的map地址有=========" + user.getMap().get("a"+i).getAddressMapName());
57        }
58        
59         return "index";
60     }
61     
62 
63 }

 

    控制台显示:

  技术分享

 数据绑定over。

 

以上是关于Spring MVC 数据绑定的主要内容,如果未能解决你的问题,请参考以下文章

Spring MVC 数据绑定

Spring MVC 和表单绑定:如何从列表中删除项目?

❤️‍Spring全家桶从入门到大神--spring mvc 参数绑定

Spring MVC 3.2 Thymeleaf Ajax 片段

Spring MVC详解(学习总结)

Spring MVC 之类型转换