Take a look at GW

【Servlet】Java Serlvet Filter 过滤器

Filter的设计思想
Filter是一种AOP(aspect-oriented programming)的设计思想 : 面向切面编程。用于的请求和响应都会走


使用filter的登录案例
我们通过一张图片理解理解filer面向切面(注意:这张图片有点表示不清楚,图中只是表明了用户请求会经过过滤器,但是响应用户也是会经过过滤器的,图中并没有表示这一点)。

下面是项目的结构:


下面是jsp文件:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.do" method="POST">
<span>用户名:</span><span><input type="text" name="uname" /></span><br/>
<span>密码:</span><span><input type="password" name="upass" /></span><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
login.jsp

下面是web.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>Filter_Demo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <!-- 设置请求的编码格式的过滤器 -->
  <filter>
    <filter-name>request</filter-name>
    <filter-class>cn.userLogin.filter.RequestFilter</filter-class>
  </filter>
  <filter-mapping>
     <filter-name>request</filter-name>
     <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  <!-- 设置响应的编码格式的过滤器 -->
  <filter>
    <filter-name>response</filter-name>
    <filter-class>cn.userLogin.filter.ResponseFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>response</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  <!-- 设置检查参数的格式编码器 -->
  <filter>
    <filter-name>param</filter-name>
    <filter-class>cn.userLogin.filter.ParamFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>param</filter-name>
    <url-pattern>*.do</url-pattern>
  </filter-mapping>
  
</web-app>
web.xml

下面是servelet文件
package cn.user.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UserLogin
 */
@WebServlet("/login.do")
public class UserLogin extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进行数据判断
        String userName=request.getParameter("uname");
        String userPassword=request.getParameter("upass");
        
        //从数据库中查询相应的信息...
        
        //将信息返回
        response.getWriter().append("姓名:"+userName+",密码:"+userPassword);
    }

}
UserLogin.java

下面是filter文件:
package cn.userLogin.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.annotation.WebFilter;

/**
 * 这个过滤器设置请求的编码格式
 */
public class RequestFilter implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //设置请求的编码格式
        request.setCharacterEncoding("utf-8");
        //放行
        chain.doFilter(request, response);
    }
    
    public void init(FilterConfig fConfig) throws ServletException {
    }

}
RequestFilter.java
package cn.userLogin.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;

/**
 * 这个过滤器设置响应的编码格式
 */
public class ResponseFilter implements Filter {
    /**
     * 过滤器销毁的时候调用
     */
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("text/html;charset=utf-8");
        //放行
        chain.doFilter(request, response);
    }

    /**
     * 过滤器初始化的时候调用
     */
    public void init(FilterConfig fConfig) throws ServletException {
    }

}
ResponseFilter.java
package cn.userLogin.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.annotation.WebFilter;

/**
 * 这个过滤器进行参数的格式检查
 */
public class ParamFilter implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //检查参数的格式
        String uName = request.getParameter("uname");
        String uPassword = request.getParameter("upass");
        if(uName == null || uPassword == null || uName.length()==0 || uPassword.length()==0){
            response.getWriter().append("你的参数格式不正常");
            return;//退出方法
        }
        chain.doFilter(request, response);
    }

    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}
ParamFilter.java

 

Filter过滤器的分界方法chain.doFilter(request,response)

上面的图片也需给的并不是非常准确,因为在用户请求到服务的时候会经过过滤器,在浏览器响应到服务器的时候也会进行过滤器的。在用户请求到服务器的时候,执行的代码就是 chain.doFilter(request, response); 之前的代码,在服务器响应浏览器的时候执行就是 chain.doFilter(request, response); 之后的代码。

比如:

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("before");
        chain.doFilter(request, response);
        System.out.println("after");
    }

我们可以看出chain.doFilter(request,response)是一个分界方法,之前的代码对应请求,之后的代码对应响应。

因此如果我们在使用的时候不指定chain.doFilter(request,response)的话,这样请求是不能到达服务器的,因此我们可以在filter组件中对请求的用户做一些处理,比如上面的案例。

 

posted @ 2017-06-28 17:08  HDWK  阅读(246)  评论(0编辑  收藏  举报