1、过滤器
什么是过滤器
过滤器是Servlet技术中的一种组件,用于在请求到达Servlet之前或响应离开Servlet之后,对请求或响应进行预处理或后处理。过滤器通常用于执行一些通用的任务,如日志记录、验证用户身份、字符编码转换等。
过滤器的应用场景
1、请求日志记录:记录请求的信息,如请求URL、参数等。 2、权限验证:检查用户是否有权限访问特定资源。 3、字符编码转换:确保请求和响应的字符编码一致。
配置过滤器
1、定义过滤器
package com.xxs.filter;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import java.io.IOException;
public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("TestFilter过滤器初始化了");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("TestFilter过滤器执行了");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("TestFilter过滤器销毁了");
}
}
2、注册过滤器
package com.xxs.filter;
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 FilterRegistrationBean<TestFilter> filterRegistration(){
FilterRegistrationBean<TestFilter> registration = new FilterRegistrationBean<>(new TestFilter());
registration.addUrlPatterns("/*");//过滤所有请求
registration.setOrder(1);//过滤器执行顺序
return registration;
}
}
2、拦截器
什么是拦截器
拦截器是Spring框架中的一部分,用于在方法调用前后、异常抛出前后执行一些操作。拦截器常用于处理事务、日志记录、权限验证等场景。
拦截器的应用场景
1、日志记录:记录方法调用的信息,如方法名、参数等。 2、事务管理:处理方法的事务提交和回滚。 3、权限验证:验证用户是否有权限执行某个方法。
配置拦截器
1、定义拦截器
package com.xxs.interceptor;
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 TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("TestInterceptor在控制器方法执行前执行");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("TestInterceptor在控制器方法执行后执行");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("TestInterceptor在请求完成后执行");
}
}
2、注册拦截器
package com.xxs.interceptor;
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 InterceptorConfig implements WebMvcConfigurer {
@Autowired
private TestInterceptor testInterceptor;
/**
* 被拦截的路径
*/
String[] addPathPatterns = {
"/**"
};
/**
* 忽略路径
*/
String[] excludePathPatterns = {
"/login/**"
};
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(testInterceptor)
.addPathPatterns(addPathPatterns)
.excludePathPatterns(excludePathPatterns);
}
}
3、AOP(切面编程)
什么是AOP
AOP是一种编程范式,它将横切关注点(如日志、事务、权限等)从应用程序的主业务逻辑中分离出来。通过在代码中定义切点(指定在何处应用横切关注点)和通知(指定在何时执行横切关注点),AOP实现了对横切关注点的模块化管理。
AOP的应用场景
1、日志记录:在方法执行前后记录日志。 2、事务管理:处理方法的事务提交和回滚。 3、性能监控:记录方法的执行时间。 4、缓存管理:在方法调用前检查缓存中是否存在结果。
配置AOP
package com.xxs.aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Aspect
@Order(1)
public class TestAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(public * com.xxs.controller..*.*(..))")
public void testPointcut(){
}
@Before("testPointcut()")
public void doBefore(JoinPoint joinPoint) {
// 在方法调用前执行的逻辑
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
}
@Around(value = "testPointcut()")
public Object doAround(ProceedingJoinPoint joinPoint) {
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
String methodName = methodSignature.getMethod().getName();
Object obj = null;
try {
System.out.println("在切点【"+methodName+"】前执行了doAround方法");
obj = joinPoint.proceed(joinPoint.getArgs());
System.out.println("在切点【"+methodName+"】后执行了doAround方法");
} catch (Throwable e) {
log.error("aop执行异常");
}
return obj;
}
@After("testPointcut()")
public void doAfter(JoinPoint joinPoint) {
// 在方法调用后执行的逻辑
System.out.println("After method execution: " + joinPoint.getSignature().getName());
}
}