zoukankan      html  css  js  c++  java
  • Spring MVC数据转换

    样例:把一个字符串封装而一个对象。
    如:username:password格式的数据ZhangSan:1234。我们把这个数据封装成一个User对象。以下分别使用属性编辑器与转换器来实现。

    1、自己定义属性编辑器

    A、写一个属性编辑器继承PropertyEditorSupport

    package cn.framelife.mvc.converter;
    
    import java.beans.PropertyEditorSupport;
    
    import cn.framelife.mvc.entity.User;
    
    public class UserEditor extends PropertyEditorSupport {
    
        public void setAsText(String text) throws IllegalArgumentException {
            System.out.println("setAsText");
            User user = new User();
            if(text != null){
                String[] items = text.split(":");
                user.setUsername(items[0]);
                user.setPassword(items[1]);
            }
            setValue(user);
        }
    
    }

    B、Controller范围的编辑器

    在Controller中注冊及使用编辑器:

    /**
         * @InitBinder注解把编辑器绑定到当前Controller中
         */
        @InitBinder
        public void initBinder(WebDataBinder binder){
            //注冊自己定义的编辑器
            binder.registerCustomEditor(User.class, new UserEditor());
        }
    
        /**
         * 第一个參数user是一个模型数据,接收页面的username用password
         * 第二个參数converterUser通过@RequestParam注解。把页面的other參数交由UserEditor转成一个User对象 
         */
        @RequestMapping("create")
        public ModelAndView createUser(User user,@RequestParam("other")User converterUser){
            System.out.println(user.getUsername()+"--"+user.getPassword());
            System.out.println(converterUser.getUsername()+"--"+converterUser.getPassword());
    
            ModelAndView view = new ModelAndView();
            view.setViewName("/success");
    
            return view;
        }

    C、 全局范围的编辑器

    实现WebBindingInitializer接口,并在实现类中注冊属性编辑器:

    package cn.framelife.mvc.converter;
    
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.support.WebBindingInitializer;
    import org.springframework.web.context.request.WebRequest;
    
    import cn.framelife.mvc.entity.User;
    
    public class MyBindingInitializer implements WebBindingInitializer {
        public void initBinder(WebDataBinder binder, WebRequest request) {
            //注冊自己定义的属性编辑器。这里能够注冊多个属性编辑器
            binder.registerCustomEditor(User.class, new UserEditor());
        }
    }

    配置WebBindingInitializer实现类:

        <!-- 配置全局范围的属性编辑器 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="webBindingInitializer">
                <bean class="cn.framelife.mvc.converter.MyBindingInitializer"></bean>
            </property>
        </bean>

    使用属性编辑器:
    和Controller范围内的使用一样

        /**
         * 第一个參数user是一个模型数据,接收页面的username用password
         * 第二个參数converterUser通过@RequestParam注解,把页面的other參数交由UserEditor转成一个User对象 
         */
        @RequestMapping("create")
        public ModelAndView createUser(User user,@RequestParam("other")User converterUser){
            System.out.println(user.getUsername()+"--"+user.getPassword());
            System.out.println(converterUser.getUsername()+"--"+converterUser.getPassword());
    
            ModelAndView view = new ModelAndView();
            view.setViewName("/success");
    
            return view;
        }

    2、转换器

    A、写一个转换器类继承Converter

    package cn.framelife.mvc.converter;
    
    import org.springframework.core.convert.converter.Converter;
    
    import cn.framelife.mvc.entity.User;
    
    /**
     * Converter<S源类型/T目标类型>
     *
     */
    public class StringToUserConverter implements Converter<String, User> {
    
        public User convert(String source) {
            User user = new User();
            if(source != null){
                String[] items = source.split(":");
                user.setUsername(items[0]);
                user.setPassword(items[1]);
            }
            return user;
        }
    }

    B、配置(mvc-servlet.xml)

        <!-- 装配转换器 -->  
        <bean id="conversionService" 
            class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <!-- 这里能够配置多个自己定义的转换器  -->
                    <bean class="cn.framelife.mvc.converter.StringToUserConverter"></bean>
                </list>
            </property>
        </bean> 
        <!-- 装配自己定义的转换器 -->
        <mvc:annotation-driven conversion-service="conversionService"/>

    C、 Controller的处理方法中接收页面数据

        /**
         * 第一个參数user是一个模型数据,接收页面的username用password
         * 第二个參数converterUser通过@RequestParam注解,把页面的other參数交由转换器StringTouserConverter转成一个User对象 
         */
        @RequestMapping("create")
        public ModelAndView createUser(User user,@RequestParam("other")User converterUser){
            System.out.println(user.getUsername()+"--"+user.getPassword());
            System.out.println(converterUser.getUsername()+"--"+converterUser.getPassword());
    
            ModelAndView view = new ModelAndView();
            view.setViewName("/success");
    
            return view;
        }

    3、注意

    假设Controller范围的属性编辑器、全局范围的属性编辑器、转换器同一时候存在,那么Spring MVC将按以下的优先顺序查找相应类型的编辑器来处理:
    查询Controller范围的属性编辑器
    查询转换器
    查询全局范围的属性编辑器

    4、数据格式化

    4.1 Spring内建的格式化转换器

    这里写图片描写叙述

    4.2 注解驱动格式化的使用

    A、启动注解驱动格式化功能
    之前我们配置自己定义转换器的时候。使用的是BeanConversionServiceFactoryBean。

    org.springframework.context.support.ConversionServiceFactoryBean

    改成

    org.springframework.format.support.FormattingConversionServiceFactoryBean

    FormattingConversionServiceFactoryBean即能够注冊自己定义的转换器。还能够注冊自己定义的注解驱动的格式转换器,使项目支持注解驱动格式化功能。

        <bean id="conversionService" 
            class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
            <property name="converters">
                <list>
                    <!-- 这是之前配置自己定义的转换器  -->
                    <bean class="cn.framelife.mvc.converter.StringToUserConverter"></bean>
                </list>
            </property>
        </bean>

    B、页面

    <form action="user/create.abc" method="post">
            用户名:<input type="text" name="username"><br/>
            密 码:<input type="text" name="password"><br/>
            生日:<input type="text" name="birthday"><br/>
            工资:<input type="text" name="salary"><br/>
            其他:<input type="text" name="other"><br/>
            <input type="submit">
     </form>

    C、实体类中使用格式化注解

    public class User implements java.io.Serializable {
        private Integer id;
        private String username;
        private String password;
    
        // 将如1999-09-09这种字符串转换成Date对象
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date birthday;
        // 把如5,500.00这个的字符串转换成long类型的数据
        @NumberFormat(pattern = "#,###.##")
        private long salary;
    
        public long getSalary() {
            return salary;
        }
    
        public void setSalary(long salary) {
            this.salary = salary;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        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;
        }
    }

    D、Controler中处理

        @RequestMapping("create")
        public ModelAndView createUser(User user){
            System.out.println(user.getBirthday()+"=="+user.getSalary());
            ModelAndView view = new ModelAndView();
            view.setViewName("/success");
    
            return view;
        }
  • 相关阅读:
    java快速排序代码
    java操作redis实现和mysql数据库的交互
    python 操作mysql数据库存
    JAVA 操作远程mysql数据库实现单表增删改查操作
    URI和URL及URN的区别
    day06_字符集设置
    day6_oracle手工建库
    day08_SGA后半部分
    day08_存储
    day05_sqlloader基础
  • 原文地址:https://www.cnblogs.com/mthoutai/p/7044795.html
Copyright © 2011-2022 走看看