关闭

过滤器写法

705人阅读 评论(0) 收藏 举报
package com.accp.util;
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 EncodingFilter implements Filter
{
  private FilterConfig filterConfig;
 
  public void destroy() {}
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
 {
   // 从web.xml中获得编码名称
   String encoding = filterConfig.getInitParameter("encoding");
   // 转换编码
   request.setCharacterEncoding(encoding);
   response.setCharacterEncoding(encoding);
   chain.doFilter(request, response);
 }
 public void init(FilterConfig filterConfig) throws ServletException
 {
   this.filterConfig = filterConfig;
 }
}
-------------------web.xml的写法,在所有servlet之上---------------------
 <filter>
  <filter-name>EncodingFilter</filter-name>
  <filter-class>com.accp.util.EncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>EncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping> 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:84228次
    • 积分:1506
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:8篇
    • 译文:0篇
    • 评论:15条
    文章分类
    最新评论