今天發現項目竟然有中文亂碼問題!? ,明明記得配置好頁面編碼和filter了,怎麼會呢?
開啟頁面發現編碼如下:
<%@ page language="java" import="java.util.*,pojo.*" pageEncoding="UTF-8"%>
過濾器也正常:
因為也考慮了AJAX的情況,所以和一般的過濾器有點區別,但是紅色部分確實被執行了.
public class Encoding implements Filter {private String charset;private String ajaxPostContentType; public static final String AJAX_POST_CONTENT_TYPE_DEFAULT = "application/x-www-form-urlencoded"; public void destroy() {// TODO Auto-generated method stub}public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {// TODO Auto-generated method stubHttpServletRequest request = (HttpServletRequest)arg0;String requestSrc = request.getQueryString();if(requestSrc !=null){arg0.setCharacterEncoding("UTF-8");arg1.setCharacterEncoding("UTF-8");arg0.getParameter("");}else{arg0.setCharacterEncoding(charset);arg1.setCharacterEncoding("text/html;charset="+charset);}arg2.doFilter(arg0, arg1);}public void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stubcharset = arg0.getInitParameter("charset");ajaxPostContentType = arg0.getInitParameter("ajaxContent");if(ajaxPostContentType == null){ajaxPostContentType = AJAX_POST_CONTENT_TYPE_DEFAULT;}}}
Web.xml中配置如下:
<filter> <filter-name>encode</filter-name> <filter-class>filter.Encoding</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encode</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
貌似該做的都做了,到底問題出在哪裡? 經過一番測試原來問題是:
<form id="trheaderform" name="trheaderform" action="lagp.do" >
仔細看了一下,沒指定提交方式,所以預設用get方式提交!改為:
<form id="trheaderform" name="trheaderform" action="lagp.do" method="post">
測試OK!
總結一下:
1。 要保證Jsp的頁面編碼是UTF-8
2。 配置好filter,強制編碼為UTF-8
3。 設定Form的提交方式為POST