姿姿霸霸~~!
贵在坚持!
posts - 106,  comments - 50,  trackbacks - 0
乱码是j2ee中一个比较常见的问题。遇到1,2个情况下,可以用new String(request.getParameter(xxx).getBytes("ISO-8859-1"),"UTF-8")来解决。遇到多的情况下,就最好用过滤器了。
1个过滤器只需要注意2个地方,类和在web.xml上面的发布。

1。在web.xml上面的发布如下:
<filter>
      
<filter-name>SetCharsetEncodingFilter</filter-name //这个是类名
      
<filter-class>org.SetCharacter</filter-class>        //这个是类的位置
      
<init-param>
          
<param-name>encoding</param-name>
          
<param-value>utf-8</param-value>
      
</init-param>
  
</filter>
  
<filter-mapping>
      
<filter-name>SetCharsetEncodingFilter</filter-name>
      
<url-pattern> /* </url-pattern>   //这个代表所有的文件遇到过滤器都要被拦截
  </filter-mapping>

2。过滤的这个类如下:
package org;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacter implements Filter {
    
protected String encoding = null;
    
protected FilterConfig filterConfig = null;
    
protected boolean ignore = true;

    
public void init(FilterConfig arg0) throws ServletException {
        
this.encoding = arg0.getInitParameter("encoding");
        String value 
= arg0.getInitParameter("imnore");
        
if(value==null){
            
this.ignore = true;
        }
else if (value.equalsIgnoreCase("true")){
            
this.ignore = true;
        }
else if(value.equalsIgnoreCase("yes")){
            
this.ignore = true;
        }

        
    }


    
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        
if(ignore||(arg0.getCharacterEncoding() == null)){
            String encoding 
=selectEncoding(arg0);
            
if(encoding!=null)
                arg0.setCharacterEncoding(encoding);
        }

        arg2.doFilter(arg0,arg1);
    }


    
private String selectEncoding(ServletRequest arg0) {
        
return (this.encoding);
    }


    
public void destroy() {
        
this.encoding = null;
        
this.filterConfig = null;
    }


}

posted on 2007-01-04 23:00 xrzp 阅读(1350) 评论(2)  编辑  收藏 所属分类: JAVA

FeedBack:
# re: j2EE中的过滤器的用法(过滤乱码)
2008-08-14 17:22 | zhongshi
请问一下,加入有一个<url-pattern> temp </url-pattern>这样的标签,那么temp表示的是什么。表示的是那一个程序,他的名字是什么呢
temp是怎样体现URL的呢?   回复  更多评论
  
# re: j2EE中的过滤器的用法(过滤乱码)
2008-08-16 21:09 | sure_xx
在web.xml文件中,以下语法用于定义映射:

1.以”/’开头和以”/*”结尾的是用来做路径映射的。

2.以前缀”*.”开头的是用来做扩展映射的。

3.“/” 是用来定义default servlet映射的。

4.剩下的都是用来定义详细映射的。比如: /aa/bb/cc.action
  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

<2007年1月>
31123456
78910111213
14151617181920
21222324252627
28293031123
45678910

常用链接

留言簿(4)

随笔分类

随笔档案

好友的blog

搜索

  •  

积分与排名

  • 积分 - 115201
  • 排名 - 505

最新评论

阅读排行榜

评论排行榜