Spring MVC自定义类型转换器

来源:互联网 发布:网络兼职客服招聘 编辑:程序博客网 时间:2024/05/18 09:09

Spring MVC自定义类型转换器一般分为以下几步:

  • 定义一个类实现Converter接口,其中接口主要内容是实现两个类型之间的转换。
  • 在Spring MVC的配置文件中将刚才添加的Converter类进行配置。
  • @RequestMapping修饰的方法中使用Converter进行转换之后的类型入参。

下面看一个示例:

首先我们定义了一个实现Converter接口的对象,这里我们的UserConverter将一个String类型的变量直接转换成User类型,User中间包含有usernamepasswordageAddress这几个属性,我们将一个字符串以”-“进行分割进而对相应位置的属性进行复制,代码中有很多不完善的地方,这里只是对Converter的使用进行展示:

    package club.sean.converter;    import club.sean.entities.Address;    import club.sean.entities.User;    import org.springframework.core.convert.converter.Converter;    import org.springframework.stereotype.Component;    @Component    public class UserConverter implements Converter<String , User>{        @Override        public User convert(String s) {            //格式应该为以-分割            if (s.length()==0){                return new User();            }            String[] properties=s.split("-");            if (properties.length>0){                User user=new User();                user.setUsername(properties[0]);                user.setPassword(properties[1]);                user.setAge(Integer.parseInt(properties[2]));                Address add=new Address();                add.setProvince(properties[3]);                add.setCity(properties[4]);                user.setAddress(add);                return user;            }            return new User();        }    }

然后我们在Spring MVC的配置文件中对上述Converter进行配置:

    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean" >        <property name="converters">            <set>                <ref bean="userConverter"></ref>            </set>        </property>    </bean>    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

这个配置大概分为了两步:

  • 将自定义的UserConverter类型配置到ConversionServiceFactoryBean中。
  • 将上述bean 配置到Spring MVC的上下文中

然后就只需要使用了,我们在jsp页面上添加一个表单,并设置一个String类型名为user 的输入。

<form action ="/conversionService" method="post">    用户信息:<input type="text" name="user" />    <input type="submit" name="submit "/></form>

并在一个@Controller中处理这个请求:

    @RequestMapping("/conversionService")    public String ConversionService(@RequestParam(value = "user") User user){        System.out.println(user);        return "success";    }

这样在用户信息一栏输入类似于“xiaoming-123456-11-河北-邯郸”的输入就可以在@Controller中直接得到一个包含这些信息的User对象了。

阅读全文
0 0
原创粉丝点击