一個過濾各種中文亂碼的過濾器EncodingFilter
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
// 解決 get 請求中文亂碼
// 通過 tomcat 的 conf 目錄 server.xml 中 Connector 標籤加入 URIEncoding="UTF-8"
// <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
// 解決 響應 中文亂碼
response.setCharacterEncoding("utf-8");
// 解決瀏覽器解析亂碼
response.setContentType("text/html;charset=utf-8");
// 解決 MySQL 數據庫在 JDBC 中傳遞數據亂碼
// url = "jdbc:mysql://localhost:3306/數據庫名?useUnicode=true&characterEncoding=utf8&useSSL=false"
chain.doFilter(request, response);
}
}