举例说明, 将一个字符串转换成的 User 类型。
例如将字符串 1-zcd-1234-zcd@163.com-1999/12/12 转换成User 类型。
一、实体类
public class User { private Integer id; private String name; private Integer money; private String email; private Date birth; //构造器 、getter 、setter 方法省略 }
二、Controller
@Controller @RequestMapping(value="testHiddenHttpMethodFilter") public class TestHiddenHttpMethodFilter { @RequestMapping(value="dataConvertAndFormat", method=RequestMethod.GET) public String dataConvertAndFormat(Map<String, Object> map) { map.put("user", new User()); return "testMethod"; } @RequestMapping(value="testConverter", method=RequestMethod.POST) public String testConverter(User user) { System.out.println("进入testConverter"); System.out.println(user); return "success"; } }
在表单中输入一个字符串 1-zcd-1234-zcd@163.com-1999/12/12
<form action="${pageContext.request.contextPath}/testHiddenHttpMethodFilter/testConverter" method="POST" > User:<input type="text" name="user"> <br> <input type="submit" name="Submit" value="提交"> <br> </form>
下面的代码没有考虑异常情况,比如说不进行数字转换,日期转换等等。仅仅考虑正确的情况。
@Component public class UserConverter implements Converter<String, User> { @Override public User convert(String source) { User user = new User(); String[] vals = source.split("-"); System.out.println(source); System.out.println(vals); for (String s : vals) { Integer id = Integer.valueOf(vals[0]); String name = vals[1]; Integer money = Integer.valueOf(vals[2]); String email = vals[3]; Date birth = new Date(vals[4]); user.setId(id); user.setName(name); user.setMoney(money); user.setEmail(email); user.setBirth(birth); } return user; } }
最后还要在SpringMVC的配置文件中配置一下
<!-- 扫描包 --> <context:component-scan base-package="com.zcd.springmvc"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <mvc:default-servlet-handler/> //进行一下配置 <mvc:annotation-driven conversion-service="conversionService" ></mvc:annotation-driven> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="userConverter" /> </set> </property> </bean>