1.解决post请求乱码
(仅供参考)
配置拦截器
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@WebFilter(
urlPatterns = "/*",
initParams = {
@WebInitParam(name = "ENCODING", value = "UTF-8")
}
)
public class EncodingFilter implements Filter {
private String encoding = "";
@Override
//通过filterConfig获得拦截器初始化参数
public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("ENCODING");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(encoding); //解决post请求乱码,setCharacterEncoding请求体有效,对get请求无效
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
或者在web.xml配置
<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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.解决get请求乱码
修改tomcat下的server.xml
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>