SpringBoot 三种拦截http请求方式Filter,Interceptor和AOP
Spring Boot中可以通过以下三种方式拦截HTTP请求:
- Filter:使用Filter可以拦截所有的HTTP请求。实现
javax.servlet.Filter
接口,并注册到Spring容器中。
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
System.out.println("Filter intercepted: " + req.getRequestURI());
chain.doFilter(request, response);
}
}
- Interceptor:使用Interceptor可以针对Spring MVC的Controller层进行拦截。实现
HandlerInterceptor
接口,并注册到Spring MVC的配置中。
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
System.out.println("Interceptor intercepted: " + request.getRequestURI());
return true;
}
}
然后在Spring MVC的配置中添加:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor).addPathPatterns("/**");
}
}
- AOP:使用AOP可以针对服务层或者其他层进行拦截。创建一个切面(Aspect)并使用
@Pointcut
定义拦截点,然后编写对应的通知方法。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
@Before("execution(* com.example.YourController.*(..))")
public void beforeControllerMethod(Jo
评论已关闭