用過濾器來解決JSP中文亂碼問題

來源:互聯網
上載者:User

首先寫一個過濾器的類,如下:

 1 package com.util; 2  3 import java.io.IOException; 4 import java.io.UnsupportedEncodingException; 5  6 import javax.servlet.Filter; 7 import javax.servlet.FilterChain; 8 import javax.servlet.FilterConfig; 9 import javax.servlet.ServletException;10 import javax.servlet.ServletRequest;11 import javax.servlet.ServletResponse;12 import javax.servlet.http.HttpServletRequest;13 import javax.servlet.http.HttpServletRequestWrapper;14 import javax.servlet.http.HttpServletResponse;15 import javax.servlet.http.HttpSession;16 17 18 //過濾器處理表單傳到servlet的亂碼問題19 public class MyFilter implements Filter{20     //自寫一個request換掉原來的request,重寫裡面的getParemeter方法,可以設定編碼21     class MyRequest extends HttpServletRequestWrapper{22         23         @Override24         public String getParameter(String param) {25             String value = null;26             try {27                 //post28                 super.setCharacterEncoding(encoding);//把編碼轉換為encoding29                 value = super.getParameter(param);30                 if(super.getMethod().equalsIgnoreCase("GET")){31                     if(value!=null){32                         value = new String(value.getBytes("iso8859-1"),encoding);33                     }34                 }35             } catch (UnsupportedEncodingException e) {36                 // TODO Auto-generated catch block37                 e.printStackTrace();38             }39             return value;40         }41 42         public MyRequest(HttpServletRequest request) {43             super(request);44         }45         46     }47     protected String encoding=null; 48     public void destroy() { //銷毀49         // TODO Auto-generated method stub50         this.encoding=null;51     }52    //對編碼問題進行轉換53     public void doFilter(ServletRequest request, ServletResponse response,54             FilterChain chain) throws IOException, ServletException {55         // TODO Auto-generated method stub56         response.setContentType("text/html;charset="+encoding);57         //過濾未登入使用者58         HttpServletRequest req = (HttpServletRequest) request;59         HttpServletResponse resp = (HttpServletResponse) response;60         String path=req.getServletPath();61         String param=req.getQueryString();62         if(path!=null){63             path=path+"?"+param;//全請求路徑64         }65         if(path.endsWith("myAddress")||path.endsWith("myJingDong")||path.indexOf("myShouCang")!=-1||path.endsWith("updateUser")||path.indexOf("showOrder")!=-1||path.indexOf("showValidOrder")!=-1||path.indexOf("showCancelOrder")!=-1||path.indexOf("fillOrder")!=-1){66             HttpSession session = req.getSession();67             String userName = (String) session.getAttribute("username");68             if(userName == null){69                 session.setAttribute("url", path.replaceFirst("/", ""));70                 System.out.println(session.getAttribute("url"));71                 resp.sendRedirect("user.do?op=loginAction");72                 return;73             }74         }75         //把過濾器給下一個過濾器或資源處理器76         chain.doFilter(new MyRequest((HttpServletRequest) request), response); 77     }78 79     public void init(FilterConfig filterConfig) throws ServletException {80         // TODO Auto-generated method stub81         this.encoding=filterConfig.getInitParameter("encoding");//encoding在web.xml中指定82     }83 84 }

然後在web.xml對該過濾器進行註冊和映射:

<filter>    <filter-name>EncodingFilter</filter-name>    <filter-class>com.util.MyFilter</filter-class>    <init-param>       <param-name>encoding</param-name>       <param-value>utf-8</param-value>    </init-param>  </filter> <filter-mapping>     <filter-name>EncodingFilter</filter-name>     <url-pattern>/*</url-pattern> </filter-mapping>

上面寫的過濾器MyFilter類,本來只能處理post提交的資料(post是先處理後接收,get是先接收後處理)。

但是MyFilter裡面在對任何頁面過濾的時候,來了一個偷梁換柱:把原來用戶端請求的request給換掉了,換成自己定義的一個request了,即內部類MyRequest,不過該類要繼承一個類HttpServletRequestWrapper。

在自訂的一個內部類MyRequest裡面,實現了一個好強大的功能,就是重寫了request的getParameter()方法。該方法裡面即處理了post提交,又能處理get提交,返回的值就是處理後的值,所以該過濾器就能實現處理post和get提交的亂碼問題!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.