zoukankan      html  css  js  c++  java
  • 解决Request参数乱码的Filter 标签: filterencodingnullstringwebappjsp 20081026 18:26 1252人阅

    本人编写的请求编码过滤器,用于解决Request参数乱码问题,通过在web.xml中配置此Filter可以一劳永逸得解决乱码问题。

    用法非常简单,在web.xml中配置好这个Filter,使用时无需添加额外代码,按照正常方法取得参数即可。

    包括:

    <%=request.getParam("text")%>

    ${param.text}

    ....

    等等,任何取得请求参数的方法。

    web.xml中得配置,如下配置即可。

    要注意的是其中得编码一项要和response的编码一致。

    例如Jsp中,文件头设置了:

    <%@ page language="java" contentType="text/html; charset=GBK" pageEncoding="GBK"%>

    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=GBK">

    那么web.xml中的编码一项就应该修改为GBK


    设置中的FilterGetMethod参数将指明是否对Get方法进行编码转换。

    这项设置主要是针对Server.xml中的Conector元素的属性“URIEncoding”,

    该属性可以修改Get方法的编码,但是有时候我们并不能取得修改server.xml文件的权限,

    这时候就可以使用本过滤器的该项功能,将FilterGetMethod的值写为true。

    否则将不对Get方法做转换处理。

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    3.   <display-name>demo</display-name>
    4.   <filter>
    5.     <description>请求编码过滤器</description>
    6.     <display-name>Request Encoding Filter</display-name>
    7.     <filter-name>Request Encoding Filter</filter-name>
    8.     <filter-class>zerofire.servlet.encoding.RequestEncodingFilter</filter-class>
    9.     <init-param>
    10.       <description>是否忽略编码设置</description>
    11.       <param-name>ignore</param-name>
    12.       <param-value>false</param-value>
    13.     </init-param>
    14.     <init-param>
    15.       <description>是否处理Get方法</description>
    16.       <param-name>FilterGetMethod</param-name>
    17.       <param-value>false</param-value>
    18.     </init-param>
    19.     <init-param>
    20.       <description>设置编码</description>
    21.       <param-name>encoding</param-name>
    22.       <param-value>UTF-8</param-value>
    23.     </init-param>
    24.   </filter>
    25.   <filter-mapping>
    26.     <filter-name>Request Encoding Filter</filter-name>
    27.     <url-pattern>/*</url-pattern>
    28.   </filter-mapping>
    29. </web-app>

    源码RequestEncodingFilter:

    1. package zerofire.servlet.encoding;
    2. import java.io.IOException;
    3. import java.util.Enumeration;
    4. import javax.servlet.Filter;
    5. import javax.servlet.FilterChain;
    6. import javax.servlet.FilterConfig;
    7. import javax.servlet.ServletException;
    8. import javax.servlet.ServletRequest;
    9. import javax.servlet.ServletResponse;
    10. import javax.servlet.http.HttpServletRequest;
    11. /**
    12.  * 请求编码过滤器,过滤所有请求,将请求参数字符串转换为指定编码,避免乱码出现
    13.  * 使用方法:
    14.  * 在web.xml中配置此Filter过滤所有路径,使用时无需任何额外代码,直接取参数即可
    15.  * 支持Post方法和Get方法得请求。
    16.  * 
    17.  * @author Zero
    18.  * @version 1.2
    19.  * @since 2003, 2008
    20.  *
    21.  */
    22. public class RequestEncodingFilter implements Filter {
    23.     protected FilterConfig config;
    24.     protected String encoding;
    25.     protected boolean ignore;
    26.     protected boolean filterGetMethod;
    27.     public RequestEncodingFilter() {
    28.         config = null;
    29.         encoding = null// 编码,默认为UTF-8
    30.         ignore = false// 可选,默认为不忽略
    31.         filterGetMethod = false// 是否处理Get方法
    32.     }
    33.     @Override
    34.     public void destroy() {
    35.         config = null;
    36.         encoding = null;
    37.     }
    38.     @Override
    39.     public void init(FilterConfig filterConfig) throws ServletException {
    40.         config = filterConfig;
    41.         
    42.         Enumeration names = config.getInitParameterNames();
    43.         while(names.hasMoreElements()) {
    44.             String name = names.nextElement().toString();
    45.             
    46.             if (name.trim().toLowerCase().equals("encoding")) {
    47.                 encoding = filterConfig.getInitParameter(name);
    48.                 if (encoding == null || encoding.trim().length() == 0) {
    49.                     encoding = "utf-8";
    50.                 }
    51.             }
    52.             
    53.             if (name.trim().toLowerCase().equals("ignore")) {
    54.                 String s = config.getInitParameter(name);
    55.                 if (s == null) s = "";
    56.                 s = s.trim().toLowerCase();
    57.                 ignore = (s.equals("true") || s.equals("yes") || s.equals("ignore"));
    58.             }
    59.             
    60.             if (name.trim().toLowerCase().equals("filtergetmethod")) {
    61.                 String s = config.getInitParameter(name);
    62.                 if (s == null) s = "";
    63.                 s = s.trim().toLowerCase();
    64.                 filterGetMethod = (s.equals("true") || s.equals("yes"));
    65.             }
    66.         }
    67.     }
    68.     @Override
    69.     public void doFilter(ServletRequest req, ServletResponse resp,
    70.             FilterChain chain) throws IOException, ServletException {
    71.         HttpServletRequest request = (HttpServletRequest) req;
    72.         if (!ignore) {
    73.             request.setCharacterEncoding(encoding);
    74.             // 对于GET方法需要对QueryString重新编码
    75.             if (filterGetMethod 
    76.                     && "GET".equalsIgnoreCase(request.getMethod())
    77.                     && (request.getQueryString() != null)) {
    78.                 req = new RequestEncodingWrapper(request, encoding);
    79.             }
    80.         }
    81.         chain.doFilter(req, resp);
    82.     }
    83. }


    RequestEncodingWrapper

     

    1. package zerofire.servlet.encoding;
    2. import java.io.UnsupportedEncodingException;
    3. import java.util.Iterator;
    4. import java.util.Map;
    5. import javax.servlet.http.HttpServletRequest;
    6. import javax.servlet.http.HttpServletRequestWrapper;
    7. /**
    8.  * 供RequestEncodingFilter使用。
    9.  * 作用是转换一个HttpServletRequest,转换其取得参数的函数,避免出现乱码
    10.  * @author Zero
    11.  * 
    12.  */
    13. public class RequestEncodingWrapper extends HttpServletRequestWrapper {
    14.     private String encoding;
    15.     /**
    16.      * @param request
    17.      */
    18.     public RequestEncodingWrapper(HttpServletRequest request) {
    19.         this(request, "utf-8");
    20.     }
    21.     public RequestEncodingWrapper(HttpServletRequest request, String enc) {
    22.         super(request);
    23.         encoding = enc;
    24.     }
    25.     private static String getEncodedString(String value, String enc)
    26.             throws UnsupportedEncodingException {
    27.         return new String(value.getBytes("ISO-8859-1"), enc);
    28.     }
    29.     @Override
    30.     public String getParameter(String key) {
    31.         String ret = super.getParameter(key);
    32.         if (ret != null) {
    33.             try {
    34.                 ret = getEncodedString(ret, encoding);
    35.             } catch (UnsupportedEncodingException ex) {
    36.                 ex.printStackTrace();
    37.             }
    38.         }
    39.         return ret;
    40.     }
    41.     @SuppressWarnings("unchecked")
    42.     @Override
    43.     public Map getParameterMap() {
    44.         Map map = super.getParameterMap();
    45.         if (map != null) {
    46.             Iterator it = map.keySet().iterator();
    47.             while (it.hasNext()) {
    48.                 Object obj = map.get(it.next());
    49.                 if (obj != null) {
    50.                     try {
    51.                         obj = getEncodedString((String) obj, encoding);
    52.                     } catch (UnsupportedEncodingException ex) {
    53.                         ex.printStackTrace();
    54.                     }
    55.                 } // if (obj != null)
    56.             } // while (it.hasNext)
    57.         } // if (map != null)
    58.         return map;
    59.     }
    60.     @Override
    61.     public String[] getParameterValues(String key) {
    62.         String[] ret = super.getParameterValues(key);
    63.         if (ret != null) {
    64.             for (int i = 0; i < ret.length; i++) {
    65.                 try {
    66.                     ret[i] = getEncodedString(ret[i], encoding);
    67.                 } catch (UnsupportedEncodingException ex) {
    68.                     ex.printStackTrace();
    69.                 }
    70.     
    71.             }
    72.         }
    73.         return ret;
    74.     }
    75. }

     

  • 相关阅读:
    vs2005 enable your debug
    暑假的安排
    session
    我所看过的电影——不断更新中……
    symbian
    CUDA学习。。。visual assist 扩展
    MySQL密码修改
    fcitx in Fedora
    LDAP身份验证
    mysql自增auto_increment删除记录
  • 原文地址:https://www.cnblogs.com/zerofire/p/7162172.html
Copyright © 2011-2022 走看看