`

Spring MVC数据绑定大全

 
阅读更多
Spring MVC数据绑定大全 .

刚开始用spring mvc 做web开发时,经常会不知道如何合适绑定页面数据.用惯struts2的朋友更认为spring mvc 绑定数据不如struts2方便(本人最开始也是这么认为),经过一段时间的应用和测试,总结出以下几种情况,希望对刚接触spring mvc 的朋友有所帮助.

示例程序下载

查看spring源码可以看出spring支持转换的数据类型已经很多了.



org.springframework.beans.PropertyEditorRegistrySupport.java

    /**
         * Actually register the default editors for this registry instance.
         */ 
        private void doRegisterDefaultEditors() { 
            this.defaultEditors = new HashMap<Class, PropertyEditor>(64); 
            // Simple editors, without parameterization capabilities.  
            // The JDK does not contain a default editor for any of these target types.  
            this.defaultEditors.put(Charset.class, new CharsetEditor()); 
            this.defaultEditors.put(Class.class, new ClassEditor()); 
            this.defaultEditors.put(Class[].class, new ClassArrayEditor()); 
            this.defaultEditors.put(Currency.class, new CurrencyEditor()); 
            this.defaultEditors.put(File.class, new FileEditor()); 
            this.defaultEditors.put(InputStream.class, new InputStreamEditor()); 
            this.defaultEditors.put(Locale.class, new LocaleEditor()); 
            this.defaultEditors.put(Pattern.class, new PatternEditor()); 
            this.defaultEditors.put(Properties.class, new PropertiesEditor()); 
            this.defaultEditors.put(Resource[].class, new ResourceArrayPropertyEditor()); 
            this.defaultEditors.put(TimeZone.class, new TimeZoneEditor()); 
            this.defaultEditors.put(URI.class, new URIEditor()); 
            this.defaultEditors.put(URL.class, new URLEditor()); 
            // Default instances of collection editors.  
            // Can be overridden by registering custom instances of those as custom editors.  
            this.defaultEditors.put(Collection.class, new CustomCollectionEditor(Collection.class)); 
            this.defaultEditors.put(Set.class, new CustomCollectionEditor(Set.class)); 
            this.defaultEditors.put(SortedSet.class, new CustomCollectionEditor(SortedSet.class)); 
            this.defaultEditors.put(List.class, new CustomCollectionEditor(List.class)); 
            this.defaultEditors.put(SortedMap.class, new CustomMapEditor(SortedMap.class)); 
            // Default editors for primitive arrays.  
            this.defaultEditors.put(byte[].class, new ByteArrayPropertyEditor()); 
            this.defaultEditors.put(char[].class, new CharArrayPropertyEditor()); 
            // The JDK does not contain a default editor for char!  
            this.defaultEditors.put(char.class, new CharacterEditor(false)); 
            this.defaultEditors.put(Character.class, new CharacterEditor(true)); 
            // Spring's CustomBooleanEditor accepts more flag values than the JDK's default editor.  
            this.defaultEditors.put(boolean.class, new CustomBooleanEditor(false)); 
            this.defaultEditors.put(Boolean.class, new CustomBooleanEditor(true)); 
            // The JDK does not contain default editors for number wrapper types!  
            // Override JDK primitive number editors with our own CustomNumberEditor.  
            this.defaultEditors.put(byte.class, new CustomNumberEditor(Byte.class, false)); 
            this.defaultEditors.put(Byte.class, new CustomNumberEditor(Byte.class, true)); 
            this.defaultEditors.put(short.class, new CustomNumberEditor(Short.class, false)); 
            this.defaultEditors.put(Short.class, new CustomNumberEditor(Short.class, true)); 
            this.defaultEditors.put(int.class, new CustomNumberEditor(Integer.class, false)); 
            this.defaultEditors.put(Integer.class, new CustomNumberEditor(Integer.class, true)); 
            this.defaultEditors.put(long.class, new CustomNumberEditor(Long.class, false)); 
            this.defaultEditors.put(Long.class, new CustomNumberEditor(Long.class, true)); 
            this.defaultEditors.put(float.class, new CustomNumberEditor(Float.class, false)); 
            this.defaultEditors.put(Float.class, new CustomNumberEditor(Float.class, true)); 
            this.defaultEditors.put(double.class, new CustomNumberEditor(Double.class, false)); 
            this.defaultEditors.put(Double.class, new CustomNumberEditor(Double.class, true)); 
            this.defaultEditors.put(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, true)); 
            this.defaultEditors.put(BigInteger.class, new CustomNumberEditor(BigInteger.class, true)); 
            // Only register config value editors if explicitly requested.  
            if (this.configValueEditorsActive) { 
                StringArrayPropertyEditor sae = new StringArrayPropertyEditor(); 
                this.defaultEditors.put(String[].class, sae); 
                this.defaultEditors.put(short[].class, sae); 
                this.defaultEditors.put(int[].class, sae); 
                this.defaultEditors.put(long[].class, sae); 
            } 
        } 







1.基本数据类型

很简单,该怎么写就怎么写.

controller代码

    @RequestMapping 
        public void test1(String name, Integer age, Double income, Boolean isMarried, String[] interests) 
        { 
            System.out.println("简单数据类型绑定========="); 
            System.out.println("名字:" + name); 
            System.out.println("年龄:" + age); 
            System.out.println("收入:" + income); 
            System.out.println("已结婚:" + isMarried); 
            System.out.println("兴趣:"); 
            for (String interest : interests) 
            { 
                System.out.println(interest); 
            } 
            System.out.println("===================="); 
        } 





jsp代码

    <form action="test1.do" method="post"> 
        <div class="f_left">姓名:</div> 
        <div class="f_left"><input name="name" value="张三"/></div> 
        <div class="clear"></div> 
        <div class="f_left">年龄:</div> 
        <div class="f_left"><input name="age" value="20"/></div> 
        <div class="clear"></div> 
        <div class="f_left">收入:</div> 
        <div class="f_left"><input name="income" value="100000"/></div> 
        <div class="clear"></div> 
        <div class="f_left">结婚:</div> 
        <div class="f_left"> 
        <input type="radio" name="isMarried" value="true" checked="checked"/>是 
        <input type="radio" name="isMarried" value="false"/>否</div> 
        <div class="clear"></div> 
        <div class="f_left">兴趣:</div> 
        <div class="f_left"> 
        <input type="checkbox" name="interests" value="听歌" checked="checked"/>听歌 
        <input type="checkbox" name="interests" value="书法" checked="checked"/>书法 
        <input type="checkbox" name="interests" value="看电影" checked="checked"/>看电影 
        </div> 
        <div class="clear"></div> 
        <div><input type="submit" value="提交表单"/></div> 
    </form> 







2.简单对象类型

与基本类型相拟,只不过绑定到对象上更加简洁.(类拟struts的ActionForm)

controller代码

    @RequestMapping 
        public void test2(User user) 
        { 
            System.out.println("简单对象类型绑定========="); 
            System.out.println("名字:" + user.getName()); 
            System.out.println("年龄:" + user.getAge()); 
            System.out.println("收入:" + user.getIncome()); 
            System.out.println("已结婚:" + user.getIsMarried()); 
            System.out.println("========================"); 
        } 





user代码

    public class User { 
        private String name; 
        private Integer age; 
        private Boolean isMarried; 
        private Double income; 
        private String[] interests; 
         
        public String getName() { 
            return name; 
        } 
        public void setName(String name) { 
            this.name = name; 
        } 
        public Integer getAge() { 
            return age; 
        } 
        public void setAge(Integer age) { 
            this.age = age; 
        } 
        public Boolean getIsMarried() { 
            return isMarried; 
        } 
        public void setIsMarried(Boolean isMarried) { 
            this.isMarried = isMarried; 
        } 
        public Double getIncome() { 
            return income; 
        } 
        public void setIncome(Double income) { 
            this.income = income; 
        } 
        public String[] getInterests() { 
            return interests; 
        } 
        public void setInterests(String[] interests) { 
            this.interests = interests; 
        } 
    } 





jsp代码

    <form action="test2.do" method="post"> 
            <div class="f_left">姓名:</div> 
            <div class="f_left"><input name="name" value="lxf"/></div> 
            <div class="clear"></div> 
            <div class="f_left">年龄:</div> 
            <div class="f_left"><input name="age" value="20"/></div> 
            <div class="clear"></div> 
            <div class="f_left">收入:</div> 
            <div class="f_left"><input name="income" value="100000"/></div> 
            <div class="clear"></div> 
            <div class="f_left">结婚:</div> 
            <div class="f_left"> 
            <input type="radio" name="isMarried" value="true" checked="checked"/>是 
            <input type="radio" name="isMarried" value="false"/>否</div> 
            <div class="clear"></div> 
            <div class="f_left">兴趣:</div> 
            <div class="f_left"> 
            <input type="checkbox" name="interests" value="听歌" checked="checked"/>听歌 
            <input type="checkbox" name="interests" value="书法" checked="checked"/>书法 
            <input type="checkbox" name="interests" value="看电影" checked="checked"/>看电影 
            </div> 
            <div class="clear"></div> 
            <div><input type="submit" value="提交表单"/></div> 
        </form> 







3.List类型绑定

网上很多人都给不出答案,关键在于,List需要绑定在对象(ActionForm),直接写在request-mapping函数的参数是不行的,更重要的一点是要创建对象(ArrayList).

controller代码

    @RequestMapping 
        public void test3(Club club) 
        { 
            System.out.println("list类型绑定========="); 
            System.out.println("会员:"); 
            for (User user : club.getUsers()) 
            { 
                System.out.println(user.getName()); 
            } 
            System.out.println("========================"); 
        } 





Club代码

    public class Club { 
        private List<User> users = new ArrayList<User>(); 
         
        public List<User> getUsers() { 
            return users; 
        } 
         
        public void setUsers(List<User> users) { 
            this.users = users; 
        } 
    } 





jsp代码

    <form action="test3.do" method="post"> 
            <div class="f_left">会员1号:</div> 
            <div class="f_left"> 
            <input name="users[0].name" value="张三"/> 
            </div> 
            <div class="clear"></div> 
            <div class="f_left">会员2号:</div> 
            <div class="f_left"> 
            <input name="users[1].name" value="李四"/> 
            </div> 
            <div class="clear"></div> 
            <div class="f_left">会员3号:</div> 
            <div class="f_left"> 
            <input name="users[2].name" value="王五"/> 
            </div> 
            <div class="clear"></div> 
            <div><input type="submit" value="提交表单"/></div> 
        </form> 







4.Set类型绑定

与List类型相似,经测试表明,绑定Set数据时,必须先在Set对象中Add相应的数量的模型对象.

controller代码

    @RequestMapping 
        public void test4(Club2 club) 
        { 
            System.out.println("set类型绑定========="); 
            System.out.println("会员:"); 
            for (User user : club.getUsers()) 
            { 
                System.out.println(user.getName()); 
            } 
            System.out.println("========================"); 
        } 


Club2代码





    public class Club2 { 
        private Set<User> users = new LinkedHashSet<User>(); 
         
        public Club2() { 
            users.add(new User()); 
            users.add(new User()); 
            users.add(new User()); 
        } 
         
        public Set<User> getUsers() { 
            return users; 
        } 
        public void setUsers(Set<User> users) { 
            this.users = users; 
        } 
    } 







jsp代码

    <form action="test4.do" method="post"> 
            <div class="f_left">会员1号:</div> 
            <div class="f_left"> 
            <input name="users[0].name" value="张三"/> 
            </div> 
            <div class="clear"></div> 
            <div class="f_left">会员2号:</div> 
            <div class="f_left"> 
            <input name="users[1].name" value="李四"/> 
            </div> 
            <div class="clear"></div> 
            <div class="f_left">会员3号:</div> 
            <div class="f_left"> 
            <input name="users[2].name" value="王五"/> 
            </div> 
            <div class="clear"></div> 
            <div><input type="submit" value="提交表单"/></div> 
        </form> 







5.Map类型绑定

最灵活的一种方式,可无限绑定未定义的参数,注意必须绑定在对象下(ActionForm).

controller代码

    @RequestMapping 
        public void test5(UserForm userForm) 
        { 
            System.out.println("Map类型绑定========="); 
            System.out.println("名字:" + userForm.getUser().get("name")); 
            System.out.println("年龄:" + userForm.getUser().get("age")); 
            System.out.println("收入:" + userForm.getUser().get("income")); 
            System.out.println("已结婚:" + userForm.getUser().get("isMarried")); 
            System.out.println("========================"); 
        } 





UserForm.java代码

    public class UserForm { 
        private Map<String, String> userMap = new LinkedHashMap<String, String>(); 
        private User user = new User(); 
         
        public Map<String, String> getUserMap() { 
            return userMap; 
        } 
        public void setUserMap(Map<String, String> userMap) { 
            this.userMap = userMap; 
        } 
        public User getUser() { 
            return user; 
        } 
        public void setUser(User user) { 
            this.user = user; 
        } 
         
    } 





jsp代码

    <form action="test5.do" method="post"> 
            <div class="f_left">姓名:</div> 
            <div class="f_left"><input name="user['name']" value="张三"/></div> 
            <div class="clear"></div> 
            <div class="f_left">年龄:</div> 
            <div class="f_left"><input name="user['age']" value="20"/></div> 
            <div class="clear"></div> 
            <div class="f_left">收入:</div> 
            <div class="f_left"><input name="user['income']" value="100000"/></div> 
            <div class="clear"></div> 
            <div class="f_left">结婚:</div> 
            <div class="f_left"> 
            <input type="radio" name="user['isMarried']" value="true" checked="checked"/>是 
            <input type="radio" name="user['isMarried']" value="false"/>否</div> 
            <div class="clear"></div> 
            <div><input type="submit" value="提交表单"/></div> 
        </form> 







6.复合类型绑定

controller代码

    @RequestMapping 
        public void test6(UserForm userForm) 
        { 
            System.out.println("复合类型绑定========="); 
            System.out.println("名字:" + userForm.getUser().getName()); 
            System.out.println("年龄:" + userForm.getUser().getAge()); 
            System.out.println("收入:" + userForm.getUser().getIncome()); 
            System.out.println("已结婚:" + userForm.getUser().getIsMarried()); 
            System.out.println("========================"); 
        } 





UserForm代码

    public class UserForm { 
        private Map<String, String> userMap = new LinkedHashMap<String, String>(); 
        private User user = new User(); 
         
        public Map<String, String> getUserMap() { 
            return userMap; 
        } 
        public void setUserMap(Map<String, String> userMap) { 
            this.userMap = userMap; 
        } 
        public User getUser() { 
            return user; 
        } 
        public void setUser(User user) { 
            this.user = user; 
        } 
         
    } 





jsp代码

    <form action="test6.do" method="post"> 
        <div class="f_left">姓名:</div> 
        <div class="f_left"><input name="user.name" value="张三"/></div> 
        <div class="clear"></div> 
        <div class="f_left">年龄:</div> 
        <div class="f_left"><input name="user.age" value="20"/></div> 
        <div class="clear"></div> 
        <div class="f_left">收入:</div> 
        <div class="f_left"><input name="user.income" value="100000"/></div> 
        <div class="clear"></div> 
        <div class="f_left">结婚:</div> 
        <div class="f_left"> 
        <input type="radio" name="user.isMarried" value="true" checked="checked"/>是 
        <input type="radio" name="user.isMarried" value="false"/>否</div> 
        <div class="clear"></div> 
        <div><input type="submit" value="提交表单"/></div> 
    </form> 
分享到:
评论

相关推荐

    spring MVC数据绑定大全

    在Spring MVC中,数据绑定是一项核心功能,它允许开发者将用户输入的数据与控制器中的对象属性进行关联,简化了数据处理的复杂性。本文将详细介绍Spring MVC中的数据绑定,并提供实例帮助初学者理解。 1. **模型...

    Spring MVC数据绑定大全.rar

    "Spring MVC数据绑定大全.rar"这个压缩包很可能包含了全面讲解Spring MVC数据绑定技术的资料,如"Spring MVC数据绑定大全.pdf"。下面将详细阐述Spring MVC数据绑定的关键知识点。 1. **注解驱动的数据绑定**:...

    spring mvc 参数绑定漏洞

    3. **默认配置不当**:Spring MVC的默认配置可能允许过于宽松的数据绑定,例如允许空值绑定到非null字段,或者允许任意类型的参数绑定。 针对这些风险,开发者可以采取以下措施来增强Spring MVC应用的安全性: 1. *...

    Spring MVC数据绑定概述及原理详解

    以下是对Spring MVC数据绑定的深入解释: **数据绑定概述** 在Spring MVC中,数据绑定是通过`DataBinder`组件实现的。当一个HTTP请求到达控制器方法时,Spring MVC会自动创建一个`DataBinder`实例,并使用`...

    Spring MVC jar包

    - **基本概念**:Spring MVC提供了一个灵活的MVC实现,包括请求映射、视图解析、模型绑定等功能。它通过DispatcherServlet作为前端控制器,负责接收请求并分发到相应的处理器。 - **组件**:主要包括Model、View、...

    第12章Spring MVC参数绑定的验证

    在Spring MVC中,对于如int、String等基本数据类型的请求参数,Spring MVC会自动将其与控制器方法的参数进行匹配和绑定。例如,一个GET请求中的查询参数`id=123`会被自动绑定到控制器方法的`int id`参数上。 2. **...

    SpringMVCDemo:Spring MVC 框架知识案例

    1.创建第一个 Spring MVC 程序案例 ...11.Spring MVC 数据绑定案例 12.Spring MVC 实现 JSON 数据返回案例 13.Spring MVC 文件的上传与下载案例 14.Spring MVC 拦截器案例 15.Spring MVC 异常处理案例

    最全最经典spring-mvc教程

    Spring MVC还支持数据绑定,自动将请求参数绑定到Java对象,这极大地简化了表单提交的处理。对于验证,Spring MVC提供了BindingResult和Validator接口,用于校验模型数据的正确性。 另外,Spring MVC与Spring框架的...

    Spring MVC 4.2.3

    5. **数据绑定和验证**:Spring MVC提供强大的数据绑定功能,将HTTP请求参数自动映射到处理方法的参数,并支持JSR-303/JSR-349 Bean Validation标准进行数据验证。 6. **异常处理**:通过定义全局异常处理器,可以...

    Mastering Spring MVC 4(2015.09)源码

    总的来说,"Mastering Spring MVC 4(2015.09)源码"提供了深入学习Spring MVC的机会,你可以通过阅读和分析源码来了解如何配置DispatcherServlet、怎样编写控制器、如何进行数据绑定与验证,以及如何利用拦截器等特性...

    spring mvc 4.0

    6. **数据绑定与验证**:Spring MVC提供了数据绑定和验证功能,允许将表单数据自动绑定到Java对象,并进行校验,简化了业务逻辑处理。 7. **视图解析**:Spring MVC 4.0支持多种视图技术,如JSP、FreeMarker、...

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    除此之外,Spring MVC还支持数据绑定、验证、本地化、主题、异常处理等功能。例如,使用@ModelAttribute注解可以将请求参数绑定到Controller方法的参数上,@Valid用于进行数据验证,Validator接口可以自定义验证逻辑...

    Spring MVC + Mybatis+Spring实现的个人博客系统

    这是一个基于Spring MVC、Mybatis和Spring框架实现的个人博客系统,涵盖了Web开发中的后端架构设计、数据库管理和前端展示等多个方面。以下将详细介绍这个系统的关键知识点: **1. Spring MVC** Spring MVC是Spring...

    spring mvc框架依赖全面jar

    `org.springframework.web.servlet-3.1.1.RELEASE.jar` 是Spring MVC的主要组件,它负责处理HTTP请求,提供模型-视图-控制器的实现,包括控制器、视图解析和模型数据绑定等功能。 `org.springframework.web-3.1.1....

    spring MVC_快速入门

    Spring MVC支持自动的数据绑定,可以将请求参数直接绑定到Controller方法的参数上,也可以将表单数据绑定到Java对象。此外,@Valid用于验证模型数据,配合Validator接口实现自定义校验规则。 7. **异常处理** ...

    Spring MVC使用Demo

    首先,Spring MVC的设计模式基于Model-View-Controller(MVC),它将应用程序的业务逻辑、数据和用户界面进行了分离,使得代码更加清晰、易于维护。在Spring MVC中,Controller处理用户的请求,Model存储数据,而...

    27 Spring MVC数据绑定InitBinder揭秘慕课专栏1

    背景在使用 SpingMVC 框架的项目中,经常会遇到页面某些数据要转换成类型是 Date、Integer、Double 等的数据绑定到控制器的实体。Sprin

    spring mvc jar包

    以上这些库构成了 Spring MVC 开发的基础环境,开发者可以利用它们来创建控制器、定义模型、配置视图解析器,以及实现事务管理、数据访问等复杂功能。通过 Spring MVC,开发者能够以声明式的方式组织应用程序,提高...

Global site tag (gtag.js) - Google Analytics