JavaWeb項目的中文亂碼的原因以及Servlet中處理GET請求和POST請求編碼過濾器
一、亂碼原因
①傳輸方和接收方采用的編碼不一致。傳輸方對參數采用的是UTF-8編碼而接收方卻用GBK進行解析,當然是亂碼。
②Tomcat服務器默認采用的ISO8859-1編碼得到參數值。雖然①中采用了同樣的編碼方式,但經過tomcat一處理,也會出現亂碼(GET方式)
二、解決辦法
方法一 每次傳輸都手動設置編碼(GET方式傳輸數據)
傳輸方
String name = URLEncoder.encode("張三","UTF-8");
String path = "https://localhost:8008/xyWeb/xyServlet?name=" + name;
接收方
String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
若傳輸方默認采用UTF-8編碼就沒有必要每次寫,但接收方每次都寫太煩,可考慮過濾器。
方法二(過濾器)
/** * 編碼過濾器 * * @author xy * */ public class EncodingFilter implements Filter { private String encoding; public void init(FilterConfig fConfig) throws ServletException { encoding = fConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception { HttpServletRequest httprequest = (HttpServletRequest) request; if ("GET".equals(httprequest.getMethod())) { // 將httpRequest進行包裝 EncodingHttpServletRequest wrapper = new EncodingHttpServletRequest(httprequest, encoding); chain.doFilter(wrapper, response); } else { request.setCharacterEncoding(encoding); response.setContentType("text/html;charset=" + encoding); chain.doFilter(request, response); } } public void destroy() { } } /** * httpRequest進行包裝類 * * @author xy * */ public class EncodingHttpServletRequest extends HttpServletRequestWrapper { private HttpServletRequest request; private String encoding; public EncodingHttpServletRequest(HttpServletRequest request) { super(request); this.request = request; } public EncodingHttpServletRequest(HttpServletRequest request,String encoding) { super(request); this.request = request; this.encoding = encoding; } @Override public String getParameter(String name) { String value = request.getParameter(name); if (null != value) { try { // tomcat默認以ISO8859-1處理GET傳來的參數。把tomcat上的值用ISO8859-1獲取字節流,再轉換成UTF-8字符串 value = new String(value.getBytes("ISO8859-1"), encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return value; } }
<filter> <display-name>EncodingFilter</display-name> <filter-name>EncodingFilter</filter-name> <filter-class>cn.xy.filter.EncodingFilter</filter-class> <init-param> <description></description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
最後更新:2017-04-03 20:19:30
上一篇:
Oracle性能優化學習筆記之選擇最有效率的表名順序
下一篇:
C# 關於類型轉換 麵試題
私人定製——使用深度學習Keras和TensorFlow打造一款音樂推薦係統
hdu 1556 Color the ball 樹狀數組
MaxCompute模板與樣例
cf 153.div2 D. Playing with Permutations
Dev BarManager控件要通過Remove成員來釋放內存
Phalcon入門教程之模型CURD(1)
Java SSM 商戶管理係統 客戶管理 庫存管理 進銷存 項目源碼 springmvc
hibernate之映射關係多對多
How the cloud is enabling a mobile workforce
Java 運算符