Filter过滤器的简单使用测试

1\了解过滤器的声明周期

2\过滤器的web.xml文件的配置


 <filter>
	  <filter-name>EncodingFilter</filter-name>
	  <filter-class>com.gyarmy.demo1.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>


3\过滤器的使用


package com.gyarmy.demo1;

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;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter {

	private FilterConfig config;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		//方便滴啊用API
		HttpServletRequest request =  (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)resp;
		
		//设置编码
		String encoding = config.getInitParameter("encoding");
		System.out.println(encoding);
		response.setContentType("text/html;charset="+encoding);
		
		//禁止缓存数据
		response.setHeader("cache-control", "no-cache");
		response.setHeader("pragma", "no-cache");
		response.setDateHeader("expires", 0);
		
		
		chain.doFilter(request, response);
		
		
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.config = filterConfig;
	}

}






原文链接: Filter过滤器的简单使用测试 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( https://gyarmy.com/post-84.html )

发表评论

0则评论给“Filter过滤器的简单使用测试”