Intellij IDEA Spring MVC解决中文乱码
在配置了IDEA的编码格式后,在接受的前端数据仍然有中文乱码的问题,其解决步骤有:
- 设置Tomcat的编码格式:
- 打开设置在Editor—>File Encodings将其设置为 UTF-8
- 我在配置了上面两步后仍然是乱码,最后在SpringMVC的web.xml文件中添加过滤器将其解决,步骤如下(当然以下这是自己写的类配置乱码问题,第四步是Spring MVC提供的类,与自己写的文件配置大同小异):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>myFilter</filter-name>
//自己定义的过滤器类路径
<filter-class>cn.com.SpringMvc.filter.SolverTrubleForLanguage</filter-class>
<init-param>
<param-name>setEncoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Java过滤器代码
public class SolverTrubleForLanguage implements Filter {
private String setEncoding;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
/**读取文件进行编码格式的设置*/
this.setEncoding = filterConfig.getInitParameter("setEncoding");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding(setEncoding);
servletResponse.setContentType("text/html; charset=UTF-8");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
- Spring MVC提供的类解决乱码
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置请求中的中文乱码问题-->
<filter>
<filter-name>SpringMVCFilter</filter-name>
//SpringMVC提供的类
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SpringMVCFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
-
最终结果展示
客户端:
服务端: