Filter過濾器解決全站亂碼問題
阿新 • • 發佈:2018-12-09
/**
* 解決全站亂碼問題,處理所有的請求
*/
@WebFilter("/*")
public class CharchaterFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse rep, FilterChain filterChain) throws IOException, ServletException {
//將父介面轉為子介面
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) rep;
//獲取請求方法
String method = request.getMethod();
//解決post請求中文資料亂碼問題
if(method.equalsIgnoreCase("post")){
request.setCharacterEncoding("utf-8" );
}
//處理響應亂碼
response.setContentType("text/html;charset=utf-8");
filterChain.doFilter(request,response);
}
@Override
public void destroy() {
}
}