Java拦截器应用
原创 已于 2024-10-21 18:04:46 修改 · 粉丝可见 · 1k 阅读 · 10 · 12 GEO检测 · 编辑
文章链接:https://blog.csdn.net/hacker_51/article/details/143116625
目录
[TOC]
Java拦截器
在Java Web开发中,拦截器(Interceptor)是一种非常重要的设计模式,它允许你在请求到达目标资源之前或之后执行某些操作。这种模式在多种框架中都有应用,比如Java Servlet中的 HttpServlet ,Spring框架的 HandlerInterceptor ,以及Java EE中的 Container Managed Interceptors 。本文将详细介绍Java拦截器的概念、原理以及如何在实际项目中应用它们。
拦截器的概念
拦截器是一种动态拦截方法调用的机制,类似于过滤器。Spring框架中提供的,用来动态拦截控制器方法的执行。它可以拦截请求,在指定的方法调用前后,根据业务需要执行预先设定的代码。
拦截器的原理
拦截器通常通过定义一系列的拦截点(intercept points)来工作。这些拦截点定义了拦截器在请求处理过程中的执行时机。典型的拦截点包括:
preHandle() :在 请求处理之前 调用(如Controller方法之前)。
postHandle() :在 请求处理之后 调用,但在视图渲染之前(如Controller方法之后)。
afterCompletion() :在 请求完全结束 后调用,如渲染了视图之后。
应用实例
拦截器可以通过结合 JWT令牌( 登录校验JWT令牌-CSDN博客 ),全局捕获异常( Java全局捕获异常处理器-CSDN博客 )这两个模块完成登录校验的操作。
由于登录校验的操作有未登录的情况,在Java异常类中,有 RuntimeException 和 Exception 等各类的异常,并不存在我们想要描述的异常类。所以这里我们可以自定义一个异常类。
自定义异常类
在Java编程中,异常处理是一个重要的概念,它允许程序在遇到错误或意外情况时,能够优雅地处理而不是直接崩溃。Java提供了一套内置的异常类,但有时候这些内置的异常类可能不足以满足我们的需求。在这种情况下,我们可以创建自定义异常类来更精确地描述特定的错误情况。
什么是自定义异常类?
自定义异常类是用户定义的异常类,它继承自Java的 Exception 类或其子类。通过创建自定义异常类,我们可以提供更详细的错误信息,并且可以控制异常的处理方式。
如何创建自定义异常类?
创建自定义异常类非常简单,通常只需要继承 相应的Java内置的异常 类即可,比如最常见直接继承大的 Exception类 ,并添加一些构造函数来满足不同的需求。
比如以下是我自定义的一个登录异常类。
1 2 3 4
| public class LoginException extends RuntimeException{ private Integer code; }
|
最后通过IDEA的 Alt + Ins 键 快速对这个异常类的方法生成即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class LoginException extends RuntimeException{ private Integer code;
public LoginException(Integer code) { this.code = code; }
public LoginException(String message, Integer code) { super(message); this.code = code; }
public LoginException(String message, Throwable cause, Integer code) { super(message, cause); this.code = code; }
public LoginException(Throwable cause, Integer code) { super(cause); this.code = code; }
public LoginException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) { super(message, cause, enableSuppression, writableStackTrace); this.code = code; } }
|
全局捕获异常器中指定自定义异常类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import com.project.blog.constant.BaseConstant; import com.project.blog.result.Result; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice public class GlobalExceptionHandler {
@ExceptionHandler(LoginException.class) public Result ex(LoginException ex){ String message = ex.getMessage(); return Result.error(BaseConstant.CODE_RUNNING_ERROR,message); }
@ExceptionHandler(Exception.class) public Result ex(Exception ex) { ex.printStackTrace(); String message = ex.getMessage(); return Result.error(message); } }
|
拦截器应用
注册拦截器
创建一个拦截器类, 实现 HandlerInterceptor 接口。
1 2 3 4
| import org.springframework.web.servlet.HandlerInterceptor; @Component public class LoginCheckInterceptor implements HandlerInterceptor { }
|
通过 IDEA 的 Alt + Ins 键 快速重写生成即可获得拦截器的架构,并根据需求更改拦截逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| 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 LoginCheckInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("拦截器的 preHandle 方法开始运行...."); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("拦截器的 postHandle 方法开始运行...."); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("拦截器的 afterCompletion 方法开始运行...."); } }
|
配置拦截器
创建一个WebConfig 类, 实现 WebMvcConfigurer 接口,重写 addInterceptors 方法 。
addInterceptors方法:
.addInterceptor(LoginCheckInterceptor) // 配置拦截器
.addPathPatterns(“/**“) // 配置 拦截的路径 其中 /** 表示拦截所有资源
.excludePathPatterns(“/login”); // 不需要拦截那些资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import lombok.extern.slf4j.Slf4j; 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; @Slf4j @Configuration public class WebConfig implements WebMvcConfigurer {
@Autowired private LoginCheckInterceptor loginCheckInterceptor;
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginCheckInterceptor) .addPathPatterns("/**") .excludePathPatterns("/login"); } }
|
| 拦截路径 |
含义 |
举例 |
| /* |
一级路径 |
能匹配/depts,/emps,/login,不能匹配/depts/1 |
| /** |
任意级路径 |
能匹配/depts,/depts/1,/depts/1/2 |
| /depts/* |
/depts下的一级路径 |
能匹配/depts/1,不能匹配/depts/1/2,/depts |
| /depts/** |
/depts下的任意级路径 |
能匹配/depts,/depts/1,/depts/1/2,不能匹配/emps/1 |
登录校验拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| import com.project.blog.constant.BaseConstant; import com.project.blog.exception.LoginException; import com.project.blog.utils.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
@Slf4j @Component public class LoginCheckInterceptor implements HandlerInterceptor {
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { log.info("拦截器的 preHandle 方法开始运行...."); String url = request.getRequestURL().toString(); log.info("请求的地址:{}", url);
String jwt = request.getHeader("token"); log.info("token:{}", jwt);
if (!StringUtils.hasLength(jwt)) { throw new LoginException(BaseConstant.LOGIN_JWT_NULL_ERROR, BaseConstant.CODE_RUNNING_ERROR); }
try { JwtUtils.parseJwt(jwt); } catch (Exception e) { log.info("解析令牌失败,返回未登录信息"); throw new LoginException(BaseConstant.LOGIN_JWT_ERROR, BaseConstant.CODE_RUNNING_ERROR); } log.info("令牌合法,放行"); return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { log.info("拦截器的 postHandle 方法开始运行...."); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { log.info("拦截器的 afterCompletion 方法开始运行...."); } }
|