import org.springframework.web.servlet.HandlerInterceptor; 解释
时间: 2023-09-27 11:10:07 浏览: 94
`org.springframework.web.servlet.HandlerInterceptor` 是 Spring 框架中的一个接口,用于拦截 HTTP 请求并在处理请求之前或之后执行一些操作。它是一个拦截器接口,可以在请求被处理前或者处理后进行拦截并进行相应的处理。在 Spring MVC 中,可以使用 `HandlerInterceptor` 来实现一些常见的拦截需求,例如权限控制、日志记录、请求参数验证等。通过实现 `HandlerInterceptor` 接口,开发者可以自定义拦截器,并将其添加到 Spring MVC 拦截器链中,在请求被处理前或者处理后执行自定义的拦截器逻辑。
相关问题
package com.de.debook.interceptor; import com.de.debook.entity.User; import com.de.debook.constant.WebConstant; 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; import javax.servlet.http.HttpSession; @Component public class AuthorityInterceptor implements HandlerInterceptor { // 权限拦截器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); User user = (User) session.getAttribute(WebConstant.SESSION_KEY_USER); // 用户未登录状态返回登录页面 if (user == null) { response.sendRedirect("/user/login.html"); 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 { } }
这段代码是一个权限拦截器,用于拦截未登录用户的访问。在 preHandle 方法中,首先获取 HttpSession 中的 User 对象,如果 User 为 null,说明用户未登录,此时将请求重定向到登录页面,并返回 false,拦截请求。如果 User 不为 null,说明用户已经登录,放行请求,返回 true。其他两个方法没有实现,不做处理。
package com.interceptor; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSONObject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import com.annotation.IgnoreAuth; import com.entity.EIException; import com.entity.TokenEntity; import com.service.TokenService; import com.utils.R; /** * 权限(Token)验证 */ @Component public class AuthorizationInterceptor implements HandlerInterceptor { public static final String LOGIN_TOKEN_KEY = "Token"; @Autowired private TokenService tokenService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //支持跨域请求 response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); IgnoreAuth annotation; if (handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class); } else { return true; } //从header中获取token String token = request.getHeader(LOGIN_TOKEN_KEY); /** * 不需要验证权限的方法直接放过 */ if(annotation!=null) { return true; } TokenEntity tokenEntity = null; if(StringUtils.isNotBlank(token)) { tokenEntity = tokenService.getTokenEntity(token); } if(tokenEntity != null) { request.getSession().setAttribute("userId", tokenEntity.getUserid()); request.getSession().setAttribute("role", tokenEntity.getRole()); request.getSession().setAttribute("tableName", tokenEntity.getTablename()); request.getSession().setAttribute("username", tokenEntity.getUsername()); return true; } PrintWriter writer = null; response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); try { writer = response.getWriter(); writer.print(JSONObject.toJSONString(R.error(401, "请先登录"))); } finally { if(writer != null){ writer.close(); } } // throw new EIException("请先登录", 401); return false; } }
这段代码是一个Spring Boot应用程序中的拦截器,用于验证用户的Token令牌是否有效。它会在每个请求之前拦截并验证Token,如果Token有效则允许请求继续进行,否则返回一个401错误并提示用户先登录。其中,@IgnoreAuth注解表示该请求不需要验证Token。这段代码还支持跨域请求,设置了一些CORS相关的header信息。
阅读全文