Springboot中使用拦截器、过滤器、监听器
在Spring Boot中,你可以通过以下方式实现拦截器、过滤器和监听器:
- 拦截器(Interceptor): 使用Spring MVC的
HandlerInterceptor
。
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 在请求处理之前进行调用
return true; // 如果返回false,则停止流程,api不会被调用
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
// 请求处理之后进行调用,但是在视图被渲染之前
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
// 在整个请求结束之后调用,也就是在DispatcherServlet渲染了视图执行
}
}
然后注册拦截器:
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 CustomInterceptor customInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(customInterceptor)
.addPathPatterns("/**"); // 拦截所有请求
}
}
- 过滤器(Filter): 实现
javax.servlet.Filter
接口。
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class CustomFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 过滤器初始化
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// 可以在调用chain.doFilter(request, response)之前进行你想要的操作
chain.doFilter(request, response); // 继续执行其他的过滤器或servlet
// 可以在调用chain.doFilter(request, response)之后进行你想要的操作
}
@Override
public void destroy() {
// 过滤器销毁
}
}
评论已关闭