解決中文亂碼的過濾器
1.新建一個類 CndoFilter
package com.cndo.cndoFilter.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;
import javax.servlet.http.HttpServlet;
public class CndoFilter extends HttpServlet implements Filter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;utf-8");
fc.doFilter(req, resp);
}
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2.修改配置檔案web.xml
<filter>
<filter-name>filter</filter-name>
<filter-class>com.cndo.cndoFilter.filter.CndoFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
3.上面的配置檔案中的url-pattern為“/*”,所以在jsp的form中任何action都會通過過濾器,如果把配置檔案中的<url-pattern>/*</url-pattern>,改為<url-pattern>*.do</url-pattern>則action為*.do時才會通過過濾器