J2EE中的过滤器的用法(过滤乱码)

本文介绍了一种解决J2EE应用中乱码问题的方法,通过配置过滤器统一字符编码,确保请求参数正确解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

乱码是j2ee中一个比较常见的问题。遇到12个情况下,可以用new String(request.getParameter(xxx).getBytes("ISO-8859-1"),"UTF-8")来解决。遇到多的情况下,就最好用过滤器了。
1
个过滤器只需要注意2个地方,类和在web.xml上面的发布。<o:p></o:p>

 

1。在web.xml上面的发布如下:<o:p></o:p>

  1.    <filter>
  2.       <filter-name>SetCharsetEncodingFilter</filter-name> //这个是类名
  3.        <filter-class>org.SetCharacter</filter-class>   //这个是类的位置
  4.        <init-param>
  5.            <param-name>encoding</param-name>
  6.            <param-value>utf-8</param-value>
  7.        </init-param>
  8.    </filter>
  9.    <filter-mapping>
  10.        <filter-name>SetCharsetEncodingFilter</filter-name>
  11.         <url-pattern> /* </url-pattern>//这个代表所有的文件遇到过滤器都要被拦截
  12.    </filter-mapping>

 

2。过滤的这个类如下:<o:p></o:p>

  1.  package org;
  2.  import java.io.IOException;
  3.  import javax.servlet.Filter;
  4.  import javax.servlet.FilterChain;
  5.  import javax.servlet.FilterConfig;
  6.  import javax.servlet.ServletException;
  7.  import javax.servlet.ServletRequest;
  8.  import javax.servlet.ServletResponse;
  9.   public class SetCharacter implements Filter {
  10.      protected String encoding = null;
  11.      protected FilterConfig filterConfig = null;
  12.      protected boolean ignore = true;
  13.       public void init(FilterConfig arg0) throws ServletException {
  14.          this.encoding = arg0.getInitParameter("encoding");
  15.          String value = arg0.getInitParameter("imnore");
  16.           if(value==null){
  17.              this.ignore = true;
  18.           }else if (value.equalsIgnoreCase("true")){
  19.              this.ignore = true;
  20.           }else if(value.equalsIgnoreCase("yes")){
  21.              this.ignore = true;
  22.          }
  23.          
  24.      }
  25.       public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
  26.           if(ignore||(arg0.getCharacterEncoding() == null)){
  27.              String encoding =selectEncoding(arg0);
  28.              if(encoding!=null)
  29.                  arg0.setCharacterEncoding(encoding);
  30.          }
  31.          arg2.doFilter(arg0,arg1);
  32.      }
  33.       private String selectEncoding(ServletRequest arg0) {
  34.          return (this.encoding);
  35.      }
  36.       public void destroy() {
  37.          this.encoding = null;
  38.          this.filterConfig = null;
  39.      }
  40.  }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值