JavaWeb--中文亂碼小結
出處:http://chriszz.sinaapp.com
0.純粹html亂碼:
換個editor吧(有時候notepad都比sublime_text好用),最好是在<head></head>之間添加<meta charset="utf-8">
1.jsp到jsp之間,表單
(假設包含表單的頁面為a,提交的action為b)
get:不亂碼
post:亂碼(在b頁面用<%request.setCharacterEncoding("utf-8");%>)
超鏈接形式的跳轉,如果帶有參數,本質上還是get方法,所以不會亂碼
2.jsp到jsp之間,轉發,轉發參數亂碼(<jsp:forward>+<jsp:param>)
需要在轉發標簽<jsp:forward>之前添加<%request.setCharacterEncoding("utf-8");%>
3.servlet頁面out對象輸出中文,亂碼
在相應的方法中添加response.setContentType("text/hmtl;charset=UTF-8");
4.jsp提交表單到servlet,servlet獲取表單變量亂碼
若表單是post方法:在servlet相應方法中添加request.setCharacterEncoding("UTF-8");
若表單是get方法:在servlet相應方法中添加request.setCharacterEncoding("UTF-8");,或者用getBytes轉碼并構造新的String,例如;
String username = request.getParameter("username");
String name = new String(username.getBytes("ISO-8859-1"), "UTF-8");
總結一下:
對于post方法提交的表單,獲取表單數據的頁面都要用request.setCharacterEncoding("UTF-8");對于get方式提交的表單,獲取表單數據的頁面既可以用request.setCharacterEncoding("UTF-8")也可以用getBytes()的方法構造新的String;對于使用<jsp:param>傳遞參數的情況,需要在傳遞參數前設定request.setCharacterEncoding("UTF-8");
/******************************************************************************/
經過@小沫9的提醒,我寫了一個編碼過濾器 EncodingFilter.java,并在web.xml中進行了配置。通過測試,jsp提交表單到jsp頁面、jsp提交表單到servlet、 jsp使用傳遞參數、Servlet頁面用out對象輸出,每種情況都可以不再設定 request.setCharacterEncoding(“UTF-8″),因為過濾器已經搞定了一切編碼。代碼入下:
1 package chris.filter 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 public class PageEncodingFilter implements Filter{ 15 16 private String encoding = "UTF-8"; 17 protected FilterConfig filterConfig; 18 19 20 public void init(FilterConfig filterConfig) throws ServletException { 21 this.filterConfig = filterConfig; 22 //本過濾器默認編碼是UTF-8,但也可以在web.xml配置文件里設置自己需要的編碼 23 if(filterConfig.getInitParameter("encoding") != null) 24 encoding = filterConfig.getInitParameter("encoding"); 25 } 26 27 public void doFilter(ServletRequest srequset, ServletResponse sresponse, 28 FilterChain filterChain) throws IOException, ServletException { 29 HttpServletRequest request = (HttpServletRequest)srequset; 30 request.setCharacterEncoding(encoding); 31 HttpServletResponse response = (HttpServletResponse)sresponse; 32 response.setCharacterEncoding(encoding); 33 filterChain.doFilter(srequset, sresponse); 34 } 35 36 public void destroy() { 37 this.encoding = null; 38 } 39 40 }
相應地,我在web.xml中的filter則設定為:
1 <filter> 2 <filter-name>Encoding</filter-name> 3 <filter-class>chris.filter.PageEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>UTF-8</param-value> 7 </init-param> 8 </filter> 9 10 <filter-mapping> 11 <filter-name>Encoding</filter-name> 12 <url-pattern>/*</url-pattern> 13 </filter-mapping>
文章列表