自定义拦截器
spring mvc 拦截器
实现HandlerInterceptor
接口
spring-webmvc
包下面,可以获取HttpServletRequest
和HttpServletResponse
等web对象实例。接口请求时,
spring MVC
拦截器能够自动拦截接口,做权限校验等操作
使用场景:日志记录,统计,权限认证等
- 自定义拦截器,实现
HandlerInterceptor
接口,重写接口的三个方法
public class LoggerAnnotationInterceptor implements HandlerInterceptor
{
//目标方法执行前执行
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception
{
//eg:
if(false){
return false;
}
return true;
}
//目标方法执行后执行,如果preHandle方法返回false,不会执行到该方法
@Override
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception
{
}
//请求完成时执行
@Override
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception
{
//这里可以实现统一日志记录
}
}
- 配置拦截器
<mvc:interceptors>
<ref bean="customerSpringMvcInterceptor" />
<ref bean="loggerAnnotationInterceptor" />
</mvc:interceptors>
spring 拦截器
实现MethodInterceptor
接口
spring-aop
包下面,拦截的目标是方法
- 自定义拦截器,实现
MethodInterceptor
接口,重写invoke
方法
public class DbAnnotationInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
//额外功能,例如方法上加了某个注解@
if(methodInvocation.getMethod().isAnnotationPresent(*.class)){
//todo
}
return methodInvocation.proceed();
}
}
- 配置
<bean id="dbAnnotationInterceptor"
class="*.DbAnnotationInterceptor">
</bean>
<aop:config>
<!--切点,表达式用于匹配目标方法-->
<aop:pointcut id="dbAnnotionPoint"
expression="@annotation(*.annotation.Database) " />
<!--通知器,-->
<aop:advisor pointcut-ref="dbAnnotionPoint"
advice-ref="dbAnnotationInterceptor" />
</aop:config>
全局异常处理
使用@RestControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
if (e instanceof ArithmeticException) {
return "data exception";
} else if (e instanceof BusinessException){
return "business exception";
} else {
return "server exception";
}
}
}