在Spring Boot中,你可以通过实现HandlerInterceptor
接口来创建自定义的HTTP拦截器,用以处理诸如登录验证、权限检查等逻辑。下面将分别介绍如何创建处理“需要登录”、“不需要登录”、“需要权限”和“不需要权限”的拦截器。
1. 创建自定义拦截器
首先,你需要创建一个类实现HandlerInterceptor
接口,并实现其preHandle
、postHandle
和afterCompletion
方法(尽管你可能只需要实现preHandle
来进行权限检查)。
示例拦截器
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 你可以在这里检查登录状态或权限
// 例如,检查是否有名为"isAuthenticated"的session属性
boolean isAuthenticated = request.getSession().getAttribute("isAuthenticated") != null;
// 示例:检查是否需要登录
if (需要登录 && !isAuthenticated) {
response.sendRedirect("/login");
return false; // 返回false表示拦截器链中断
}
// 示例:检查权限
// 假设handler是一个Controller的方法,可以通过反射等方式获取注解信息,这里简化为直接判断
String requiredRole = "ADMIN"; // 假设需要ADMIN权限
// 这里应该检查handler是否有权限注解,并获取所需权限,此处仅为示例
if (需要权限 && !"ADMIN".equals(request.getSession().getAttribute("role"))) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
return true; // 返回true表示继续执行下一个拦截器
}
// 你可以根据需要实现postHandle和afterCompletion方法
}
2. 注册拦截器
接下来,你需要在Spring MVC配置中注册这个拦截器。如果你使用的是Java配置(即@Configuration
类),可以这样做:
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("/**") // 拦截所有请求
.excludePathPatterns("/login", "/static/**", "/error"); // 排除不需要拦截的路径
}
}
3. 区分需要登录、不需要登录、需要权限和不需要权限的路径
在CustomInterceptor
的preHandle
方法中,你可以通过检查请求的URL或其他方式来区分这些路径。然而,更常见的做法是在注册拦截器时,通过excludePathPatterns
方法排除不需要拦截的路径(如登录页面、静态资源等),并在preHandle
方法中实现具体的登录和权限检查逻辑。
4. 注意事项
- 确保在需要的地方设置session属性,例如用户登录成功后设置
isAuthenticated
和role
等。 - 考虑到安全和性能,不要将敏感信息(如密码)存储在session中。
- 拦截器的执行顺序可以通过
InterceptorRegistry
的order()
方法进行调整。 - 在
preHandle
方法中返回false
会中断拦截器链,并停止处理当前请求。返回true
则会继续执行下一个拦截器或处理器。