什么才是最好处理中文方法

问题提出: 看了不少文章处理中文,比如:在 jsp里写
// 传统方式 
<% @ page contentType = " text/html; charset=gb2312 "   %>  
< html >  
< body >  
< form  method =post  action =test.jsp >  
< input  type =text  name =your_name >  
</ form >  
<% =   new   String (request.getParameter( " your_name " ).getBytes( " 8859_1 " ),  " GB2312 " %>  
</ body >  
</ html >  

// 新的方式 
<% @ page contentType = " text/html; charset=gb2312 "   %>  
<%  request.setCharacterEncoding( " GB2312 " );  %>  
< html >  
< body >  
< form  method =post  action =test.jsp >  
< input  type =text  name =your_name >  
</ form >  
<% =  request.getParameter( " your_name " %>  
</ body >  
</ html >  
那是相当不好的方法,现在介绍一个朋友教我的方法:

问题解决方法:
步骤1:先写一个servlet  EncodingFilter.java
 1 import  javax.servlet.FilterChain;
 2 import  javax.servlet.ServletRequest;
 3 import  javax.servlet.ServletResponse;
 4 import  java.io.IOException;
 5 import  javax.servlet.Filter;
 6 import  javax.servlet.http.HttpServletRequest;
 7 import  javax.servlet.ServletException;
 8 import  javax.servlet.FilterConfig;
 9
10 public   class  EncodingFilter  implements  Filter  {
11
12      private  String targetEncoding  =   " gb2312 " ;
13      protected  FilterConfig filterConfig;
14
15      public   void  init(FilterConfig config)  throws  ServletException  {
16          this .filterConfig  =  config;
17     }

18
19      public   void  doFilter(
20         ServletRequest srequest,
21         ServletResponse sresponse,
22         FilterChain chain)
23          throws  IOException, ServletException  {
24
25         HttpServletRequest request  =  (HttpServletRequest) srequest;
26         request.setCharacterEncoding(targetEncoding);  // 把请求用指定的方式编码
27          //  把处理发送到下一个过滤器
28         chain.doFilter(srequest, sresponse);
29     }

30
31      public   void  destroy()  {
32          this .filterConfig  =   null ;
33     }

34
35      public   void  setFilterConfig( final  FilterConfig filterConfig)  {
36          this .filterConfig  =  filterConfig;
37     }

38 }

39

步骤2:在web.xml里这样写
< filter >
        
< filter-name > EncodingFilter </ filter-name >
        
< display-name > EncodingFilter </ display-name >
        
< filter-class > com.itthinker.payroll.common.EncodingFilter </ filter-class >
    
</ filter >
    
< filter-mapping >
        
< filter-name > EncodingFilter </ filter-name >
        
< url-pattern > /* </ url-pattern >
    
</ filter-mapping >

总结:
这样的话,任何映射地址全部会先加载EncodingFilter,中文处理就搞定了,不用那么麻烦在每个jsp文件写那么多重复代码了,很好地做到了,代码可复用性。当然  page contentType = " text/html; charset=gb2312 "
还是要的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值