创建目录 interceptor——MyInterceptor.java文件,该文件实现 HandlerInterceptor 接口
MyInterceptor.java文件实现 HandlerInterceptor接口代码如下:
代码案例:(已验证cookie为案列)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Value("${token.name}")
String tokenName;
@Value("${token.value}")
String tokenValue;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截的请求"+request.getRequestURI());
Cookie[] cookies = request.getCookies();
for(int i = 0 , length = cookies.length ; i< length ; i++){
if(cookies[i].getName().equals(tokenName) && cookies[i].getValue().equals(tokenValue)){
return true;
}
}
request.getRequestDispatcher("/nologin").forward(request,response);
return false;
}
}
拦截器也主要有三个方法: 其中preHandle是在请求之前就进行调用,如果该请求需要被拦截,则返回false,否则true; postHandle是在请求之后进行调用,无返回值; afterCompletion是在请求结束的时候进行调用,无返回值。 |
创建目录 config —— MvcAppConfig.java文件 实现 WebMvcConfigurer接口
代码如下:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import xyz.ark.backstage_09.interceptor.MyInterceptor;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class MvcAppConfig implements WebMvcConfigurer{ //这里其实 也可以 去继承 extends WebMvcConfigurerAdapter类 重写方法
/**
* 添加拦截器
* @param registry
*/
@Bean
public MyInterceptor myInterceptor(){
return new MyInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
List list = new ArrayList();
list.add("/user/find");
list.add("/index");
//addInterceptor(添加自定义的拦截器) addPathPatterns(要拦截的路径) excludePathPatterns(放心的路径)
registry.addInterceptor(myInterceptor()).addPathPatterns(list);
}
}
搞定!!!
标签:拦截器,springboot,MyInterceptor,配置,springframework,org,import,servlet,public From: https://blog.51cto.com/u_14671216/6398485