方式一:在 tomcat 安装目录修改 server.xml 配置文件,设置编码。
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="2000"
redirectPort="8443"
URIEncoding="utf-8"/>
方式二:在 web.xml 中添加如下配置。
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
方式三:添加EncodingFilter过滤器。
在 web.xml 中添加如下配置,需要根据实际项目配置 内的路径。
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.projectname.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在项目路径下创建filter目录,在filter目录下创建EncodingFilter类过滤器。
package com.projectname.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html");
servletResponse.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest, servletResponse);
}
public void destroy() {
}
}