关于拦截器,大家一定都不陌生,spring boot 中是如何使用拦截器的呢?今天就举个例子,来给大家说明一下,废话不多说,开始撸代码!!!
1、创建一个新的spring boot项目,并引入相应的jar,pom文件如下:
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.quick
quick-intercprot
0.0.1-SNAPSHOT
jar
quick-intercprot
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-maven-plugin
2、编写HandlerInterceptor
public class TestInterceptor extends HandlerInterceptorAdapter{
private static final String username="wang";
private static final String pwd="123";
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle start...");
String usernameParam = request.getParameter("username");
String pwdParam = request.getParameter("pwd");
if(!StringUtils.isEmpty(usernameParam)&&!StringUtils.isEmpty(pwdParam)){
if(username.equals(usernameParam)&&pwdParam.equals(pwd)){
System.out.println("TRUE");
return Boolean.TRUE;
}else {
System.out.println("FALSE");
response.sendRedirect(request.getContextPath()+"/index/errorIndex");
return Boolean.FALSE;
}
}else {
return Boolean.TRUE;
}
}
}
我们创建一个名为TestInterceptor的拦截器并继承HandlerInterceptorAdapter,实现HandlerInterceptorAdapter抽象类中的preHandle方法。此处我们模拟一个登陆请求的拦截,当账号密码正确时拦截器返回true并跳转到相应的页面,如果账号密码错误,重定向到一个错误页面。
3、编写拦截器配置
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestInterceptor()).addPathPatterns("/test/**");
super.addInterceptors(registry);
}
}
由于我使用的springboot是2.0.3.RELEASE,2.0以后的版本需要继承WebMvcConfigurationSupport ,如果你使用的是2.0以下的版本请继承WebMvcConfigurerAdapter,此处做了一个请求的拦截,只有/test/**的请求才会被拦截到。
4、编写测试Controller,此处我们需要写三个Controller
此方法为模拟的登陆请求的方法
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping("/t")
public String test(String username,String pwd){
return "success";
}
}
此方法主要是为了模拟拦截器是否能够拦截特定的请求路径,故将请求写为/test2/**
@RestController
@RequestMapping("/test2")
public class Test2Controller {
@RequestMapping("/t")
public String test(String param){
return "success";
}
}
此方法主要是为了当账号密码错误时跳转错误页面
@Controller
@RequestMapping("/index")
public class IndexController {
@RequestMapping("/errorIndex")
public String index(){
return "errorIndex";
}
}
5、编写错误页面errorIndex.html
Titlelogin error,账号或者密码错误
6、启动项目,测试拦截器是否起效
因为密码错误,请求跳转到了错误页面
密码拦截器生效,下面我们测试一下固定请求拦截是否生效,我们请求一下路径http://localhost:8080/test2/t?param=123 效果如下图:
ok拦截器没有拦截/test2/**的请求,实验成功
我们来总结一下
编写HandlerInterceptor继承HandlerInterceptorAdapter实现preHandle方法
编写拦截器配置继承WebMvcConfigurationSupport实现addInterceptors方法