Spring MVC数据转换

来源:互联网 发布:地图获取数据库经纬度 编辑:程序博客网 时间:2024/06/08 00:04

例子:把一个字符串封装而一个对象。
如: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;    }
0 0
原创粉丝点击