
正文
SpringMVC框架——自定义数据类型转换器
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Spring MVC 框架的 Converter<S,T> 是一个可以将一种数据类型转换成另一种数据类型的接口,这里 S 表示源类型,T 表示目标类型。
开发中如果需要自定义数据类型转换时,实现Converter<S,T>这个接口,覆写xx方法就行了。例如:
- 将前端传来的字符串日期,转成日期类型。
1、定义DataConverter 转换类实现Converter<S,T>接口,覆写convert方法
package com.sunjian.converter;import org.springframework.core.convert.converter.Converter;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;/** * @author sunjian * @date 2020/3/18 9:21 */public class DataConverter implements Converter<String, Date> { private String pattern; public DataConverter(String pattern) { this.pattern = pattern; } @Override public Date convert(String s) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.pattern); try { return simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return null; }}
2、编写controller类
package com.sunjian.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;import java.util.Date;/** * @author sunjian * @date 2020/3/18 9:24 */@Controller@RequestMapping("/converter")public class ConverterHandler { @RequestMapping("/date") public ModelAndView dateConverter(Date date){ System.out.println(date); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("date", date); modelAndView.setViewName("converter"); return modelAndView; }}
3、在springmvc.xml文件中添加配置
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 配置自动扫描 --> <context:component-scan base-package="com.sunjian.controller"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 消息转换器 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 自定义数据类型转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.sunjian.converter.DataConverter"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven></beans>
4、编写JSP页面
date.jsp / converter.jsp
<%@page contentType="text/html; charset=UTF-8" language="java" %><%@page isELIgnored="false" %> <!-- 是否忽略解析el表达式 --><html><body><form action="/converter/date" method="post"> <input type="text" name="date">(yyyy--MM-dd) <input type="submit" value="提交"></form></body></html>
<%@page contentType="text/html; charset=UTF-8" language="java" %><%@page isELIgnored="false" %> <!-- 是否忽略解析el表达式 --><html><body>${date}</body></html>
5、浏览器访问jsp页面,提交请求


- 用户在页面表单中输入信息来创建商品信息
1、编写实体类
package com.sunjian.entity;/** * @author sunjian * @date 2020/3/18 10:18 */public class Goods { private Integer id; private String name; private double price; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "Goods{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + '}'; }}
2、编写转换器类
package com.sunjian.converter;import com.sunjian.entity.Goods;import org.springframework.core.convert.converter.Converter;/** * @author sunjian * @date 2020/3/18 10:20 */public class goodsConverter implements Converter<String, Goods> { @Override public Goods convert(String s) { Goods goods = new Goods(); String values[] = s.split(","); if (values.length == 3 && values != null) { goods.setId(Integer.parseInt(values[0])); goods.setName(values[1]); goods.setPrice(Double.parseDouble(values[2])); } else { System.out.println((String.format("参数格式错误,需要格式[%s],但格式是[%s] ", "1,水杯,108.5 ", s))); } return goods; }}
3、编写controller类
package com.sunjian.controller;import com.sunjian.entity.Goods;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;/** * @author sunjian * @date 2020/3/18 10:31 */@Controller@RequestMapping("/goods")public class GoodsController { @RequestMapping("/addGoods") public ModelAndView addGoods(@RequestParam("goods") Goods goods){ System.out.println(goods); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("goods", goods); modelAndView.setViewName("showGoods"); return modelAndView; }}
4、在springmvc.xml中注册配置转换器
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <!-- 配置自动扫描 --> <context:component-scan base-package="com.sunjian.controller"></context:component-scan> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 消息转换器 --> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 自定义数据类型转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="com.sunjian.converter.DataConverter"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg> </bean> <bean class="com.sunjian.converter.goodsConverter"></bean> </list> </property> </bean> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven></beans>
5、编写相应的JSP页面
addGoods.jsp / showGoods.jsp
<%@page contentType="text/html; charset=UTF-8" language="java" %><%@page isELIgnored="false" %> <!-- 是否忽略解析el表达式 --><html><head> <style> #goods { width: 200px; } </style></head><body><form action="/goods/addGoods" method="post"> <input type="text" name="goods" id="goods" placeholder="请输入商品:编号, 名称, 价格">(例如:1,鼠标,108.10) <input type="submit" value="提交"></form></body></html>
<%@page contentType="text/html; charset=UTF-8" language="java" %><%@page isELIgnored="false" %> <!-- 是否忽略解析el表达式 --><html><body><div> 商品编号:${goods.id}</br> 商品名称:${goods.name}</br> 商品价格:${goods.price}</div></body></html>
6、浏览器访问jsp页面,提交请求


OK.







