filter从web.xml读取config的时候中文编码问题

首先,web.xml中不建议出现超出ASCII范围的字符

但是作为一点积累,简单举个例子如下,其核心代码就是new String(String.getBytes(charset_1), charset_2)

 1 public class SimpleFilter implements Filter {

 2     

 3     private boolean enable = false;

 4     

 5     public void init(FilterConfig config)

 6           throws ServletException{

 7         String enableString = config.getInitParameter("enable");

 8         if (enableString != null && enableString.equalsIgnoreCase("true")) {

 9             this.enable = true;

10         }

11         // 这个地方你如果从xml中读中文的话,读出来就是乱码

12         // 解决编码问题暂时可行的办法如下,但是这种方法的前提是你知道xml文件的编码情况,如果不是iso-8859-1你怎么办?

13         String initParam = config.getInitParameter("ref");

14         try {

15             initParam = new String(initParam.getBytes("iso-8859-1"), "UTF-8");

16         } catch (UnsupportedEncodingException e) {

17             e.printStackTrace();

18         }

19         

20         System.out.println(this + ": init(), init-param = " + initParam);

21     }

22     public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

23             throws IOException, ServletException{

24         if (this.enable)

25             System.out.println(this + ": doFilter()") ;

26         chain.doFilter(request, response);

27     }

28     public void destroy(){

29         // clean up

30     }

31     

32 }

 

你可能感兴趣的:(web.xml)