效果如图:
首先定义拦截器:
package star.july.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 FilterDemo implements Filter{
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//访问servlet前首先访问拦截器
System.out.println("1、拦截请求资源");
//执行放行,在此条语句前为拦截请求资源,之后为拦截响应资源
chain.doFilter(request, response);
System.out.println("3、拦截响应资源");
}
public void destroy() {
}
}
package star.july.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FilterServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("2、接收资源");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
最后是对拦截器Filter的xml配置:
<filter>
<filter-name>FilterDemo</filter-name>
<filter-class>star.july.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<!-- url要跟拦截的servlet的一致 -->
<url-pattern>/FilterServlet</url-pattern>
</filter-mapping>