这个是一个简单的转换器
1页面
<form action="http://localhost:8080/springMVCapp07a/testConversionServiceConverter" method="post"> <!-- private String name; private String description; private Float price; private Date productionDate; --> <!--格式:java-javabase-12.0-2011.12.12 --> product:<input type="text" name="product"> <input type="submit" value="submit"> </form>
转换器的类
@Component public class ProcuctConverter implements Converter<String, Product> { @Override public Product convert(String source) { if(source != null) { Product product = new Product(); //java-javabase-12.0-2011.12.12 String[] values = source.split("-"); if(values != null && values.length==4) { product.setName(values[0]); product.setDescription(values[1]); product.setPrice(Float.parseFloat(values[2])); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); product.setProductionDate(new Date()); System.out.println(source + "--converter"+product); return product; } } return null; }
springmvc配置文件
<!--配置ConversionService --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="procuctConverter"/> </set> </property> </bean>
记得要在annotation上加上这句
<mvc:annotation-driven conversion-service="conversionService" />
目标action
@Controller public class testConversionService { @RequestMapping(value="/testConversionServiceConverter") public String test(@RequestParam("product") Product product ) { System.out.println("/testConversionServiceConverter"+product); return "ProductForm"; } }