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

web.xml中文参数处理
本文介绍了一种在web.xml配置文件中处理中文参数的方法。通过将读取到的中文参数从iso-8859-1编码转换为UTF-8编码,解决了因默认编码不匹配导致的乱码问题。

首先,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 }

 

转载于:https://www.cnblogs.com/qrlozte/p/3515061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值