[已解决][不完美]在servlet或者filter的init中读取web.xml遇到中文乱码

暂时没找到好的解决办法,只有自己硬编码转换,找到了我再回来补充

比如下述代码(只是为了说明乱码的问题):

 1 package org.foo.filterdemo ;
 2 
 3 import java.io.* ;
 4 
 5 import javax.servlet.* ;
 6 
 7 public class SimpleFilter implements Filter {
 8     
 9     private boolean enable = false;
10     
11     public void init(FilterConfig config)
12           throws ServletException{
13         String enableString = config.getInitParameter("enable");
14         if (enableString != null && enableString.equalsIgnoreCase("true")) {
15             this.enable = true;
16         }
17         // 这个地方你如果从xml中读中文的话,读出来就是乱码,目前我还没找到比较好的办法
18         // 暂时可行的硬编码办法就是:
19         /*
20         try {
21             initParam = new String(initParam.getBytes("iso-8859-1"), "UTF-8");
22         } catch (UnsupportedEncodingException e) {
23             e.printStackTrace();
24         }
25         */
26         String initParam = config.getInitParameter("ref") ;
27         System.out.println(this + ": init(), init-param = " + initParam);
28     }
29     public void doFilter(ServletRequest request,
30               ServletResponse response,
31               FilterChain chain)
32               throws IOException,
33                      ServletException{
34         if (this.enable) {
35             System.out.println(this + ": doFilter()") ;
36             chain.doFilter(request, response);
37         } else {
38             chain.doFilter(request, response);
39         }
40     }
41     public void destroy(){
42         // clean up
43         System.out.println(this + ": destroy()");
44     }
45 }

web.xml,注意,有一个打开和关闭的选项enable

 1 <!-- simple filter -->
 2     <filter> 
 3         <filter-name>simple-filter</filter-name> 
 4         <filter-class>org.lxh.filterdemo.SimpleFilter</filter-class> 
 5         <init-param> 
 6             <param-name>enable</param-name> 
 7             <param-value>true</param-value> 
 8         </init-param>
 9         <init-param> 
10             <param-name>ref</param-name> 
11             <param-value>这是一串中文,给SimpleFilter的</param-value> 
12         </init-param>  
13     </filter>
14     <filter-mapping>
15         <filter-name>simple-filter</filter-name>
16         <url-pattern>/*</url-pattern>
17     </filter-mapping>
posted @ 2013-07-08 17:34  rldts  阅读(131)  评论(0编辑  收藏  举报