1、处理中文乱码问题
1、在web.xml中配置编码过滤器
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--web.xml中配置SpringMVC的编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置编码格式-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--设置request、response作用域强制使用此编码格式-->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--配置过滤器映射文件-->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2、修改Tomcat编码格式
apache-tomcat-9.0.17\conf\logging.properties
3、若用到log4j日志,也需要修改编码为GBK
2、Date日期类型处理
2.1 方式一:在对象字段或Controller形参上添加上@DateTimeFormat(pattern=“yyyy-MM-dd”)
@Setter@Getter@ToString
@AllArgsConstructor@NoArgsConstructor
public class User {
private Integer id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date date;
}
2.2 方式二:在Controller类中加入以下代码
@InitBinder
public void initBinderDateType(WebDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
binder.registerCustomEditor(java.util.Date.class,new CustomDateEditor(sdf,true));
}
@RequestMapping("/test9")
public ModelAndView test9(Date d) {
System.out.println("d = [" + d + "]");
return null;
}
2.3 方式三:使用@ControllerAdvice注解,该类必须处于能被Spring扫描到的包中
@ControllerAdvice
public class DateFormatControllerAdvice {
@InitBinder
public void initBinderDateType(WebDataBinder binder){
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern("yyyy-MM-dd");
binder.registerCustomEditor(java.util.Date.class,new CustomDateEditor(sdf,true));
}
}