admin管理员组文章数量:1538107
Spring MVC Converter
Spring MVC 框架的 Converter<S,T> 是一个可以将一种数据类型转换成另一种数据类型的接口,这里 S 表示源类型,T 表示目标类型。开发者在实际应用中使用框架内置的类型转换器基本上就够了,但有时需要编写具有特定功能的类型转换器。
内置的类型转换器
在 Spring MVC 框架中,对于常用的数据类型,开发者无须创建自己的类型转换器,因为 Spring MVC 框架有许多内置的类型转换器用于完成常用的类型转换。Spring MVC 框架提供的内置类型转换包括以下几种类型。
1)标量转换器
名称 | 作用 |
---|---|
StringToBooleanConverter | String 到 boolean 类型转换 |
ObjectToStringConverter | Object 到 String 转换,调用 toString 方法转换 |
StringToNumberConverterFactory | String 到数字转换(例如 Integer、Long 等) |
NumberToNumberConverterFactory | 数字子类型(基本类型)到数字类型(包装类型)转换 |
StringToCharacterConverter | String 到 Character 转换,取字符串中的第一个字符 |
NumberToCharacterConverter | 数字子类型到 Character 转换 |
CharacterToNumberFactory | Character 到数字子类型转换 |
StringToEnumConverterFactory | String 到枚举类型转换,通过 Enum.valueOf 将字符串转换为需要的枚举类型 |
EnumToStringConverter | 枚举类型到 String 转换,返回枚举对象的 name 值 |
StringToLocaleConverter | String 到 java.util.Locale 转换 |
PropertiesToStringConverter | java.util.Properties 到 String 转换,默认通过 ISO-8859-1 解码 |
StringToPropertiesConverter | String 到 java.util.Properties 转换,默认使用 ISO-8859-1 编码 |
2)集合、数组相关转换器
名称 | 作用 |
---|---|
ArrayToCollectionConverter | 任意数组到任意集合(List、Set)转换 |
CollectionToArrayConverter | 任意集合到任意数组转换 |
ArrayToArrayConverter | 任意数组到任意数组转换 |
CollectionToCollectionConverter | 集合之间的类型转换 |
MapToMapConverter | Map之间的类型转换 |
ArrayToStringConverter | 任意数组到 String 转换 |
StringToArrayConverter | 字符串到数组的转换,默认通过“,”分割,且去除字符串两边的空格(trim) |
ArrayToObjectConverter | 任意数组到 Object 的转换,如果目标类型和源类型兼容,直接返回源对象;否则返回数组的第一个元素并进行类型转换 |
ObjectToArrayConverter | Object 到单元素数组转换 |
CollectionToStringConverter | 任意集合(List、Set)到 String 转换 |
StringToCollectionConverter | String 到集合(List、Set)转换,默认通过“,”分割,且去除字符串两边的空格(trim) |
CollectionToObjectConverter | 任意集合到任意 Object 的转换,如果目标类型和源类型兼容,直接返回源对象;否则返回集合的第一个元素并进行类型转换 |
ObjectToCollectionConverter | Object 到单元素集合的类型转换 |
类型转换是在视图与控制器相互传递数据时发生的。Spring MVC 框架对于基本类型(例如 int、long、float、double、boolean 以及 char 等)已经做好了基本类型转换。
自定义类型转换器
当 Spring MVC 框架内置的类型转换器不能满足需求时,开发者可以开发自己的类型转换器。
例如有一个应用 springMVCDemo 希望用户在页面表单中输入信息来创建商品信息。当输入“apple,10.58,200”时表示在程序中自动创建一个 new Goods,并将“apple”值自动赋给 goodsname 属性,将“10.58”值自动赋给 goodsprice 属性,将“200”值自动赋给 goodsnumber 属性。
1)创建实体类
package pers.zhang.pojo;
public class GoodsModel {
private String goodsname;
private double goodsprice;
private int goodsnumber;
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname;
}
public double getGoodsprice() {
return goodsprice;
}
public void setGoodsprice(double goodsprice) {
this.goodsprice = goodsprice;
}
public int getGoodsnumber() {
return goodsnumber;
}
public void setGoodsnumber(int goodsnumber) {
this.goodsnumber = goodsnumber;
}
}
2)创建控制器类
package pers.zhang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import pers.zhang.pojo.GoodsModel;
@Controller
@RequestMapping("/my")
public class ConverterController {
@RequestMapping("/converter")
/*
* 使用@RequestParam
* ("goods")接收请求参数,然后调用自定义类型转换器GoodsConverter将字符串值转换为GoodsModel的对象gm
*/
public String myConverter(@RequestParam("goods") GoodsModel gm, Model model) {
model.addAttribute("goods", gm);
return "showGoods";
}
}
3)创建自定义类型转换器类
自定义类型转换器类需要实现 Converter<S,T> 接口,重写 convert(S) 接口方法。
convert(S) 方法的功能是将源数据类型 S 转换成目标数据类型 T。
package pers.zhang.converter;
import org.springframework.core.convert.converter.Converter;
import pers.zhang.pojo.GoodsModel;
public class GoodsConverter implements Converter<String, GoodsModel> {
@Override
public GoodsModel convert(String source) {
// 创建一个Goods实例
GoodsModel goods = new GoodsModel();
// 以“,”分隔
String stringvalues[] = source.split(",");
if (stringvalues != null && stringvalues.length == 3) {
// 为Goods实例赋值
goods.setGoodsname(stringvalues[0]);
goods.setGoodsprice(Double.parseDouble(stringvalues[1]));
goods.setGoodsnumber(Integer.parseInt(stringvalues[2]));
return goods;
} else {
throw new IllegalArgumentException(String.format(
"类型转换失败, 需要格式'apple, 10.58,200 ',但格式是[% s ] ", source));
}
}
}
4)注册类型转换器
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework/schema/beans"
xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework/schema/mvc"
xmlns:p="http://www.springframework/schema/p"
xmlns:context="http://www.springframework/schema/context"
xsi:schemaLocation="
http://www.springframework/schema/beans
http://www.springframework/schema/beans/spring-beans.xsd
http://www.springframework/schema/context
http://www.springframework/schema/context/spring-context.xsd
http://www.springframework/schema/mvc
http://www.springframework/schema/mvc/spring-mvc.xsd">
<!--
LoginController控制器类,映射到"/login"
<bean name="/login" class="pers.zhang.controller.LoginController"/>
LoginController控制器类,映射到"/register"
<bean name="/register" class="pers.zhang.controller.RegisterController"/>
-->
<!-- 使用扫描机制扫描控制器类,控制器类都在controller包及其子包下 -->
<context:component-scan base-package="pers.zhang.controller" />
<!--注册类型转换器GoodsConverter-->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="pers.zhang.converter.GoodsConverter"/>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"/>
<!-- 使用resources过滤掉不需要dispatcherservlet的资源(即静态资源,例如css、js、html、images)。
在使用resources时必须使用annotation-driven,否则resources元素会阻止任意控制器被调用 -->
<!-- 允许css目录下的所有文件可见 -->
<mvc:resources location="/css/" mapping="/css/**" />
<!-- 允许html目录下的所有文件可见 -->
<mvc:resources location="/html/" mapping="/html/**" />
<!-- 允许css目录下的所有文件可见 -->
<mvc:resources location="/images/" mapping="/images/**" />
<!-- 完成视图的对应 -->
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
5)创建相关视图
input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/my/converter" method= "post">
请输入商品信息(格式为apple, 10.58,200):
<input type="text" name="goods" /><br>
<input type="submit" value="提交" />
</form>
</body>
</html>
showGoods.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
您创建的商品信息如下:
<!-- 使用EL表达式取出model中的goods信息 -->
商品名称为:${goods.goodsname }
商品价格为:${goods.goodsprice }
商品名称为:${goods.goodsnumber }
</body>
</html>
6)测试
本文标签: 转换器详解类型SpringMvcConverter
版权声明:本文标题:SpringMVC--Converter(类型转换器)详解 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1726967663a1092401.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论