1. 程式人生 > >Filter攔截器解決中文亂碼問題

Filter攔截器解決中文亂碼問題

建立攔截器類,需要實現javax.servlet.Filter介面

public class FilterDemo1 implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        System.err.println("伺服器啟動時呼叫此方法,只調用一次,用來初始化");
    }
    @Override
    public void destroy() {
        System.err.println("伺服器退出時呼叫此方法,只調用一次"
); } @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, HttpServletRequest request = (HttpServletRequest) arg0; HttpServletResponse response = (HttpServletResponse) arg1; MyRequest request1 = new MyRequest(request); //設定request的編碼方式 request1.setCharacterEncoding("utf-8"
); //解除攔截 chain.doFilter(request1, response); }

自定義內部類,繼承HttpServletRequestWrapper類
注:HttpServletRequestWrapper類實現了HttpServletRequest介面,重寫了介面方法

class MyRequest extends HttpServletRequestWrapper{
        private HttpServletRequest request ;
        public MyRequest(HttpServletRequest request) {
            super
(request); this.request = request; } @Override public String getParameter(String name) { String value = request.getParameter(name); //判Null空 if(value==null){ return null; } //判請求方式 if(request.getMethod().equalsIgnoreCase("POST")){ return value; } try { //轉換編碼方式 value = new String(value.getBytes("ISO-8859-1"),"utf-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return value; } }

在web.xml配置檔案中載入Filter攔截器

    <filter>
        <filter-name>FilterDemo1</filter-name>
        <filter-class>filter.demo.FilterDemo1</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>FilterDemo1</filter-name>
        <!-- /*為攔截所有請求 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>