注意問題:在學習用selvert的過濾器filter處理中文亂碼時,在filter配置初始化時用了utf-8處理中文亂碼,而在提交的jsp頁面中卻用了gbk。雖然兩種都可以出來中文亂碼,但是卻造成了處理亂碼的格式不一致。所以編譯出錯。
解決方法:所有地方都用utf-8或gbk
//過濾器類
CharactorFilter.jsp
package cn.com.Filter;
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 CharactorFilter implements Filter { //繼承Filter類
//字符編碼
String encoding=null;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if(encoding!=null){
//設置request字符編碼
request.setCharacterEncoding(encoding);
//設置response字符編碼
response.setContentType("text/html;charset="+encoding);
}
//傳遞給下一個過濾器
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
//獲取初始化參數
encoding=filterConfig.getInitParameter("encoding");
}
public void destroy() {
// TODO Auto-generated method stub
encoding=null;
}
}
web.xml
<filter> <!--注意這裡是filter,不要配置成servlet-->
<filter-name>CharactorFilter</filter-name> <!--過濾器名稱-->
<filter-class>cn.com.Filter.CharactorFilter</filter-class> <!--過濾器的完整類名-->
<init-param> <!--初始化參數-->
<param-name>encoding</param-name> <!--參數名稱-->
<param-value>utf-8</param-value> <!--參數值-->
</init-param>
</filter>
<filter-mapping> <!--過濾器映射-->
<filter-name>CharactorFilter</filter-name><!--過濾器名稱-->
<url-pattern>/*</url-pattern><!--URL映射,給所有頁面處理亂碼-->
</filter-mapping>