对进入服务器的请求和服务器返回的响应进行拦截,一般用于通用操作如:权限控制、统一编码处理、敏感字符处理,拦截路径和拦截规则如下代码:
快速入门
pom文件引入servlet和jsp依赖和tomcat7插件plugin
在com.kdy.web中创建包filter再创建一个类去实现Filter。或右键->new->create new Filter。
package com.kdy.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* 拦截路径:
* 1具体资源如"/index.jsp",
* 2目录拦截如:"/user/*"拦截servlet的路径如"/user/userServlet"或或"/jsp/*"拦截webapp目录下jsp目录下的所有资源
* 3后缀名拦截如"*.jsp",
* 4拦截所有"/*"
*/
@WebFilter("/jsp/*")
public class FilterDemo implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("FilterDemo before doFilter...");//拦截浏览器发的请求到服务器前的请求进行处理
filterChain.doFilter(servletRequest,servletResponse);//放行:处理后的请求放行到服务器对应的某个jsp或servlet
System.out.println("FilterDemo after doFilter...");//服务器处理完的响应再次来到doFilter后的代码进行再次处理之后才返回给浏览器
}
@Override
public void destroy() {
}
}
注:web.xml中配置拦截器和路径方式参考如下
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
jsp/hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>hello</title>
</head>
<body>
<h1L>hello jsp~</h1L>
<%
System.out.println("到达jsp...");
%>
</body>
</html>
过滤器链
执行顺序:优先级按照过滤器类名(字符串)自然排序
登录验证Demo
@WebFilter("/*")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)request;
//配置需要无条件放行的资源路径
String[] urls ={"/login.jsp","/imgs/","/css/","/loginServlet","/register.jsp","/registerServlet","/checkCodeServlet"};
String url = req.getRequestURL().toString();
for (String u:urls) {
if (url.contains(u)){
chain.doFilter(request,response);
return;
}
}
HttpSession session = req.getSession();
Object user = session.getAttribute("user");
if (user!=null){
chain.doFilter(request,response);
}else{
req.setAttribute("login_msg","您尚未登录!");
req.getRequestDispatcher("/jsp/login.jsp").forward(req,response);
}
}
public void init(FilterConfig config) throws ServletException {
}
}