Fork me on GitHub

过滤器

  生命周期:初始化 -----过滤-------销毁

  作用:过滤url ,特定字符

  创建方式:实现一个接口继承Filter 

package com.baidu.filter;

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;


public class Demo01 implements Filter {

	public void destroy() {
		System.out.println("过滤销毁");
	}


	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		System.out.println("请求过滤");
		MyHttpServletRequest msr=new MyHttpServletRequest((HttpServletRequest)request);
		chain.doFilter(msr, response);
		System.out.println("响应过滤");
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("过滤器初始化");
	}

}

  

    配置过滤器(web.xml)

        和配置servlet相似。

 

<filter>
    <filter-name>Demo01</filter-name>
    <filter-class>com.baidu.filter.Demo01</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>Demo01</filter-name>
    <url-pattern>/*</url-pattern>//可以设置经过过滤器的url  /*表示项目下的所有路径都得经过过滤器
  </filter-mapping>

 

      过滤器在web中的位置

    浏览器        < ------------ >         过滤器              < ------------   >              服务器

 

  注意事项

    1.配置文件中会配置Filter过滤器的位置只要符合其位置就会经过过滤器    

    2.请求完成以后响应动作也会经过过滤器 

  使用过滤器来修改编码格式,这样就不需要用每个servlet中去修改编码格式了

    

 

(使用的装饰者设计模式来实现)
package com.baidu.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MyHttpServletRequest extends HttpServletRequestWrapper {
	private HttpServletRequest request;
	public MyHttpServletRequest(HttpServletRequest request) {
		super(request);
		this.request=request;
	}
	@Override
	public String getParameter(String name) {
		//判断提交方式(get/post)
		String method = request.getMethod();
		if ("Get".equalsIgnoreCase(method)) {
			String value = super.getParameter(name);
				try {
					value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return value;
		}
		if ("post".equalsIgnoreCase(method)) {
			try {
				System.out.println(request.getCharacterEncoding());
				request.setCharacterEncoding("UTF-8");
				//value = super.getParameter(name);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return super.getParameter(name);
	}

}

 

  使用动态代理来实现实现类的增强

 

public class GenericEncodingFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		final HttpServletRequest req = (HttpServletRequest) request;
		// 增强req:(使用匿名内部类)
		HttpServletRequest myReq = (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(),
				req.getClass().getInterfaces(), new InvocationHandler() {
					
					@Override
					public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
						// 判断执行的方法是否是getParameter:
						if("getParameter".equals(method.getName())){
							// 调用的是getParameter:需要增强这个方法.
							// 判断请求方式是GET还是POST:
							String type = req.getMethod();
							if("get".equalsIgnoreCase(type)){
								String value = (String) method.invoke(req, args);
								value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
								return value;
							}else if("post".equalsIgnoreCase(type)){
								req.setCharacterEncoding("UTF-8");
							}
						}
						return method.invoke(req, args);
					}
				});
		
		chain.doFilter(myReq, response);
	}

	@Override
	public void destroy() {

	}

}

  

posted on 2017-10-14 18:47  TopTime  阅读(255)  评论(0编辑  收藏  举报