package com.comen.interceptor; import com.comen.edata.bean.User; import com.comen.edata.tools.JwtUtil; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * EDataInterceptor 继承拦截器并实现preHandle方法 * 负责对token校验 */ public class EDataInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("================>拦截器"); String ack=request.getParameter("ack"); String userName=request.getParameter("userName"); if (null !=ack && !"".equals(ack) && null !=userName && !"".equals(userName)){ User user = new User(); user.setAck(ack); user.setUserName(userName); String token = JwtUtil.createToken(user); response.setHeader("token",token); return true; }else { String token = request.getHeader("token"); if (null !=token){ ack=JwtUtil.verifyToken(token); if (null==ack){ return false; } return true; }else { return 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 { } }
配置类
package com.comen.interceptor; 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 EDataConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new EDataInterceptor()) .addPathPatterns("/**"); } }
标签:拦截器,ack,request,token,import,servlet,public From: https://www.cnblogs.com/dataleaner/p/17829060.html