Spring Boot框架的过滤器(Filters)和拦截器(Interceptors)是Java开发中常用的技术,用于处理HTTP请求的前置和后置处理。它们在实际开发中有着广泛的应用场景,例如日志记录、权限验证、请求处理时间测量等。下面我将通过一些简单的例子来展示如何在Spring Boot项目中使用过滤器和拦截器(新手学习使用)。
过滤器主要用于对请求进行预处理和响应进行后处理,适用于处理所有请求。例如,我们可以创建一个简单的过滤器来记录请求的处理时间。
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class LogFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long startTime = System.currentTimeMillis(); chain.doFilter(request, response); long endTime = System.currentTimeMillis(); System.out.println("Request processed in " + (endTime - startTime) + " ms"); System.out.println("Request URI: " + ((HttpServletRequest) request).getRequestURI()); } @Override public void destroy() { } }
接着,在Spring Boot的配置类中注册这个过滤器:
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { @Bean public FilterRegistrationBeanloggingFilter(){ FilterRegistrationBean registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new LogFilter()); registrationBean.addUrlPatterns("/api/*"); return registrationBean; } }
拦截器用于在请求到达Controller之前、Controller处理之后、响应发送之前进行拦截处理。一个常见的应用场景是进行权限验证。
首先,创建一个拦截器:
import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Component public class AuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 模拟权限验证 // 实际项目中,这里可能会检查token或session String authHeader = request.getHeader("Authorization"); if ("VALID_TOKEN".equals(authHeader)) { return true; } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // Controller方法调用之后的处理 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 请求处理完毕后的处理 } }
然后,在Spring Boot的配置类中注册拦截器:
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 WebMvcConfig implements WebMvcConfigurer { @Autowired private AuthInterceptor authInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor) .addPathPatterns("/api/private/*"); } }
以上例子展示了如何在Spring Boot应用中使用过滤器记录请求处理时间以及使用拦截器进行简单的权限验证。这些只是过滤器和拦截器的基础应用,实际应用中可以根据需求扩展和调整,适合新手学习使用。