实现拦截器
定义FilterService类,配置拦截器(urlPatterns = "/*"拦截所有请求,urlPatterns = "/getAllUser"拦截单个请求)
package com.example.demo.service;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/getAllUser")
public class FilterService implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("======您已进入过滤器======");
filterChain.doFilter(servletRequest,servletResponse);
}
}
在启动类中通过ServletComponentScan注释配置拦截的路径
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan(basePackages = "com.example.demo.service")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
通过拦截器给服务添加自定义方法
定义类中的成员,定义一个改变成员的方法
自定义方法
每次请求拦截之前调用此方法设置新类,即可完成此类的公用
拦截器
网友评论