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獲得攔截器初始化參數(shù)
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"/>