一 过滤器的作用和概述
1.1 简述
人--->检票员(filter)---> 电影院。
注意:配置多个filter的时候,要设置编号id,值越小,优先级越高,越先执行。
在3.0之后新增@WebFilter注解,当使用注解配置多个Filter时,用户无法控制其执行顺序,此时Filter过滤的顺序是按照Filter的类名来控制的,按自然排序的规则。
1.2 使用场景
场景:权限控制、用户登录(非前端后端分离场景)等,过滤非法登录
过滤器: springboot的filter 过滤器的使用_健康平安的活着的专栏-CSDN博客
监听器: springboot之HttpSessionListener的用法创建,销毁_健康平安的活着的专栏-CSDN博客_httpsessionlistener
拦截器: springboot整合拦截器intercepter_健康平安的活着的专栏-CSDN博客_springboot 拦截器
二 自定义过滤的两种方式
2.1 工程结构
2.2 配置pom文件
<!--spring boot的启动类 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.3 第一种方式
1.启动类里面增加 @ServletComponentScan,进行扫描
2.新建一个Filter类,implements Filter,并实现对应的接口
3. @WebFilter 标记一个类为filter,被spring进行扫描
urlPatterns:拦截规则,支持正则
4.控制chain.doFilter的方法的调用,来实现是否通过放行还是不放行,
如果放行: FilterChain.dofilter(res,rep);
如果不放行:调转到指定页面web应用resp.sendRedirect("/index.html"); return
2.3.1 启动类增加注解
package com.ljf.spring.boot.demo.spt.filter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* SpringBoot整合Filter 方式一
*
*/
@SpringBootApplication
@ServletComponentScan
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
2.3.2 定义一个filter类
package com.ljf.spring.boot.demo.spt.filter.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.logging.LogRecord;
/**
*SpringBoot整合Filter 方式一
*<filter>
* <filter-name>FirstFilter</filter-name>
* <filter-class>com.bjsxt.filter.FirstFilter</filter-class>
*</filter>
*<filter-mapping>
* <filter-name>FirstFilter</filter-name>
* <url-pattern>/first</url-pattern>
*</filter-mapping>
*/
@WebFilter(filterName="FirstFilter",urlPatterns="/first")
public class LoginFilter implements Filter{
// @Override
public boolean isLoggable(LogRecord record) {
return false;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("进入Filter");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("离开Filter");
}
@Override
public void destroy() {
}
}
2.3.3. 演示
2.4 第二种方式
2.4.1 自定义fitler类
package com.ljf.spring.boot.demo.spt.filter.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;
/**
*
*SpringBoot整合Filter 方式二
*
*/
public class SecondFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
System.out.println("进入SecondFilter");
arg2.doFilter(arg0, arg1);
System.out.println("离开SecondFilter");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2.4.2 启动类
package com.ljf.spring.boot.demo.spt.filter;
import com.ljf.spring.boot.demo.spt.filter.filter.SecondFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
/**
* SpringBoot整合Filter方式二
*/
@SpringBootApplication
public class App2 {
public static void main(String args[]){
SpringApplication.run(App.class, args);
}
/**
* 注册Filter
*/
@Bean
public FilterRegistrationBean getFilterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
//bean.addUrlPatterns(new String[]{"*.do","*.jsp"});
bean.addUrlPatterns("/second");
return bean;
}
}
2.4.3 访问
2.5 过滤器的小案例
2.5.1 场景描述
自定义一个过滤器:对路径中含有api字样且userName为xm的请求则放过进行,否则其他情况进行拦截。
2.5.2 工程结构
2.5.3 pom文件
<!--spring boot的启动类 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thymeleaf的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2.5.4 resources目录下静态文件
1.templates目录下:
2.static 目录下:
2.5.5 controller层
package com.ljf.spring.boot.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @ClassName: UserController
* @Description: TODO
* @Author: liujianfu
* @Date: 2021/04/01 10:26:05
* @Version: V1.0
**/
@Controller
public class UserController {
@RequestMapping("/api/show")
public String showName(String userName,Model model){
System.out.println("进入controller层了!!!"+userName);
model.addAttribute("name",userName);
return "index";//跳转到指定页面
}
}
2.5.6 自定义过滤器
package com.ljf.spring.boot.demo.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @ClassName: UserLoginFilter
* @Description: TODO
* @Author: liujianfu
* @Date: 2021/04/01 10:28:14
* @Version: V1.0
**/
/**
*SpringBoot整合Filter 方式一
*<filter>
* <filter-name>loginFilter</filter-name>
* <filter-class>com.ljf.spring.boot.demo.spt.filter.filter.UserLoginFilter</filter-class>
*</filter>
*<filter-mapping>
* <filter-name>loginFilter</filter-name>
* <url-pattern>/api/*</url-pattern>
*</filter-mapping>
*/
@WebFilter(urlPatterns = "/api/*", filterName = "loginFilter")
public class UserLoginFilter implements Filter {
/**
* 容器加载的时候调用
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("=================init loginFilter=============");
}
/**
* 请求被拦截的时候进行调用
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("doFilter loginFilter");
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
String username = req.getParameter("userName");
System.out.println("获取用户名:"+username);
if ("xm".equals(username)) {
System.out.println("======");
filterChain.doFilter(servletRequest,servletResponse);
} else {
resp.sendRedirect("/login.html");//重定向不到templates目录下页面,必须走后端一下跳转到指定页面才行
// req.getRequestDispatcher("/").forward(req,resp);
return;
}
}
/**
* 容器被销毁的时候被调用
*/
@Override
public void destroy() {
System.out.println("=========================destroy loginFilter=====================");
}
}
2.5.7 启动类
注解启动类添加注解:@ServletComponentScan //添加过滤器使用
package com.ljf.spring.boot.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
/**
* Hello world!
*
*/
@SpringBootApplication
@ServletComponentScan //添加过滤器使用
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println("用户登录=====");
}
}
2.5.8 测试
1.请求url含有api且userName=xm,放行通过
2.请求url含有api且userName=xsfdsf,拦截过滤,跳转到login.html页面