用于springboot框架拦截器的实现
此方法常用于每次请求附带token验证的后台代码(token一般会放在请求header里),同理可以用作其他用途。可以复制直接使用。
1,任意位置新建WebConfig继承WebMvcConfigurationSupport,主要是针对要放开哪些方法,比如登陆的方法,或者注册的方法,这些是不需要拦截的。
package com.lbwh.controller.login;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport{
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new PassportInterceptor()).addPathPatterns("/**").excludePathPatterns("/Login/login","/Login/LoginOut");//你复制过去只需要改括号里对应的方法路径就可以,需要放开哪几个方法,就写几个
Interceptors(registry);
}
}
2,任意位置新建PassportInterceptor实现HandlerInterceptor重写它的方法。主要是针对拦截的请求进行一些处理,比如验证请求自带的token过期没过期,过期则返回false,没过期则返回true。
package com.lbwh.controller.login;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.lbwh.utils.JwtUtils;
@Component
public class PassportInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler)
throws Exception {
//以下代码是对已经拦截的请求获取token,然后验证token是否过期,进行相应的返回
String tokens = request.getHeader("token");
String token = tokens.trim().replaceAll("/^\"|\"$/g","''");
if(token != null && !"".equals(token)){
boolean flag = JwtUtils.verify(token);//这是验证token有没有过期的方法,我先不晒出来了。后续有需求,在贴出来。
if(flag) {
return true;
}
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
JSONObject res = new JSONObject();
res.put("status","-1");
PrintWriter out = null ;
out = response.getWriter();
out.write(res.toString());
out.flush();
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}