簡單介紹JSP中文亂碼處理
1.調用JSP頁面顯示亂碼
通過瀏覽器調用JSP頁面,在客戶端瀏覽器中所有的中文內容出現亂碼。
解決:
首先確認本JSP在編輯器中保存時,使用的是GBK的編碼格式,然后在JSP頁面的開始部分添加 <%@ pageEncoding="GBK" %>就可以解決中文亂碼問題。
2.調用Servlet頁面顯示亂碼
通過瀏覽器調用Servlet,Servlet在瀏覽器中顯示內容出現亂碼
解決:
在Servlet使用response在輸出內容之前,先執行response.setContentType("text/html;charset=GBK")設定輸出內容的編碼為GBK
3.Post表單傳遞參數亂碼
通過JSP頁面、HTML頁面或者Servlet中的表單元素提交參數給對應的JSP頁面或者Servelt而JSP頁面或者Servlet接收的中文參數值亂碼。
解決:
在接收POST提交的參數之前,使用request.setCharacterEncoding("GBK")設定接收參數的內容使用GBK編碼
更好的解決方法是使用過濾器技術
- package com.htt;
- 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;
- public class Encoding implements Filter {
- public void destroy() { }
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
- request.setCharacterEncoding("GBK");
- chain.doFilter(request, response);
- }
- public void init(FilterConfig filterConfig) throws ServletException { }
- }
- Web.xml文件中的設置
- <filter>
- <filter-name>encoding</filter-name>
- <filter-class>com.htt.Encoding</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>encoding</filter-name>
- <url-pattern>/ToCh_zn</url-pattern>
- </filter-mapping>
【編輯推薦】