springboot前后端分离拦截器
时间: 2023-12-07 21:39:05 浏览: 102
以下是Spring Boot前后端分离拦截器的介绍:
1.创建一个拦截器类,实现HandlerInterceptor接口,并实现其中的三个:preHandle、postHandle和afterCompletion。其中,preHandle方法在请求处理之前进行调用,postHandle方法在请求处理之后进行调用,afterCompletion方法在视图渲染之后进行调用。
2.在Spring Boot的配置类中,使用addInterceptors方法将拦截器类添加到拦截器链中。
3.在拦截器类中,可以通过request.getSession().getAttribute()方法获取session中的用户信息,从而进行登录验证等操作。
下面是一个示例代码:
```java
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if (user == null) {
response.sendRedirect("/login");
return false;
}
return true;
}
@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 {
}
}
```
```java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/login", "/register");
}
}
```
阅读全文