jsp过滤器

作者在 2006-12-10 02:20:00 发布以下内容

实现Filter类的servlet的写法

package filtertest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class FilterEncoding extends HttpServlet implements Filter {
 String encoding;
 private static final String DEFAULT_CHARACTER_ENCODING = "UTF-8";
 public void init(FilterConfig arg0) throws ServletException {
  //get encoding from config
  encoding = arg0.getInitParameter("encoding");
 }

 public void doFilter(ServletRequest arg0, ServletResponse arg1,
   FilterChain arg2) throws IOException, ServletException {
  try{
   if ((encoding != null)&&(encoding.length()>0)){   
    arg0.setCharacterEncoding(encoding);
    System.out.println("in filter and encoding = " + encoding);
   }else{
    arg0.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
   }
  }
  catch(UnsupportedEncodingException e){
   arg0.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING);
   e.printStackTrace();
  }
  //filterChain
  arg2.doFilter(arg0,arg1);
 }
}

web.xml中的配置

<filter>
  <description>This is the description of my J2EE component</description>
  <display-name>This is the display name of my J2EE component</display-name>
  <filter-name>FilterEncoding</filter-name>
  <filter-class>filtertest.FilterEncoding</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>

<filter-mapping>
  <filter-name>FilterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

默认分类 | 阅读 2578 次
文章评论,共0条
游客请输入验证码
文章分类
最新评论