Servlet 过滤器

一、通过过滤器可以做什么  

1 对请求进行统一编码  

2 对请求进行认证

包 javax.servlet.Filter

1作用:把某些信息过滤掉

2实现 Filter 接口.

1public void doFilter (ServletRequest, ServletResponse, FilterChain)该方法完成实际的过滤操作,当客户端请求方法与过滤器设置匹配的URL时,Servlet容器将先调用过滤器的doFilter方法。FilterChain用户访问后续过滤器。

2public void init(FilterConfig filterConfig)

3public void destroy()

4web.xml中配置

qq

con.hw.controller.EncodingFilter

qq

/*

乱码处理

public void doFilter(ServletRequest arg0, ServletResponse arg1,

FilterChain arg2) throws IOException, ServletException {

HttpServletRequest request=(HttpServletRequest) arg0;

HttpServletResponse response=(HttpServletResponse) arg1;

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

response.setCharacterEncoding("utf-8");

arg2.doFilter(request, response);//通过验证

}

非法字段

public void doFilter(ServletRequest arg0, ServletResponse arg1,

FilterChain arg2) throws IOException, ServletException {

HttpServletRequest request=(HttpServletRequest) arg0;

HttpServletResponse response=(HttpServletResponse) arg1;

String jl = request.getParameter("jl");

if(jl!=null&&jl.indexOf("小狗")!=-1){

response.sendRedirect("filter.jsp");

}else{

arg2.doFilter(request, response);//放行

}

}

验证登录

public void doFilter(ServletRequest request1, ServletResponse response1,FilterChain chain) throws IOException, ServletException {HttpServletRequest request=(HttpServletRequest) request1;HttpServletResponse response=(HttpServletResponse) response1;  HttpSession session = request.getSession();  if(session.getAttribute("user")!=null){    chain.doFilter(request, response);//放行  }else{  response.sendRedirect(request.getContextPath()+"/login.jsp");  }}f3com.filter.LoginFilterf3/PersonListServlet

你可能感兴趣的:(Servlet 过滤器)