一、设置编码格式“UTF-8
”
public class WebApplication implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
/**
* load 父子容器
*
*/
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
// 加载配置文件
applicationContext.register(SpringConfig.class);
applicationContext.register(SpringMvcConfig.class);
/**
* 进行编码过滤
*/
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
// 设置编码
characterEncodingFilter.setEncoding("UFT-8");
// 设置 请求响应
characterEncodingFilter.setForceRequestEncoding(true);
characterEncodingFilter.setForceResponseEncoding(true);
/**
* 写 范围
*/
FilterRegistration.Dynamic dynamic = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
dynamic.addMappingForUrlPatterns(null,true,"/*");
// dynamic.setInitParameter("allowedMethods","GET,POST");
}
取代配置文件web.xml
中的字符集编码的配置
<!-- 添加 字符编码过滤器-->
<filter>
<filter-name>encode</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>