接收请求参数的时候
产生的中文乱码问题
可以利用SpringMVC给我们提供的一个小过滤器处理
如何自定义类型转换器
Converter
1.自定义一个类
2.实现上面这个接口
接口是支持泛型 Converter<String,Type>
3.重写接口中的转换方法
方法内部该做具体转化的事情
方法会返回一个转化后的对象
4.告知Spring这里有一个自定义的类型转换器
需要让Spring帮我们加载并管理起来
配置<bean>
-----------------------------------------------------------
接收请求参数的时候
@RequestParam注解 变量 Map
@RequestHeader注解 接收协议头数据
@CookieValue
@RequestBody注解(JSON) 接收 key=value;key=value 放在参数前面
注解只能接收post请求方式 post请求是存在协议体(参数)
get请求只有协议头没有协议体
@ResponseBody注解(JSON) 响应
@ModelAttribute注解
放在某一个方法上面
方法在请求的方法执行之前先执行的(块 init)
package util;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
System.out.println("自定义转换器");
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date = sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="controller"></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<!--加载一个自定义类型转换器-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="util.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!--需要手动配置这个类的驱动-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
</beans>