Spring Boot 中如何使用拦截器(十五)

关于拦截器,大家一定都不陌生,spring boot 中是如何使用拦截器的呢?今天就举个例子,来给大家说明一下,废话不多说,开始撸代码!!!

1、创建一个新的spring boot项目,并引入相应的jar,pom文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.quick</groupId>
	<artifactId>quick-intercprot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>quick-intercprot</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.3.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>login error,账号或者密码错误</h1>
</body>
</html>

6、启动项目,测试拦截器是否起效

首先我们访问http://localhost:8080/test/t?username=wang&pwd=123 路径,如果现实一下页面,则表示账号密码正确,登陆成功

然后我们将pwd修改为1234,http://localhost:8080/test/t?username=wang&pwd=1234 ,页面显示如下:

因为密码错误,请求跳转到了错误页面
密码拦截器生效,下面我们测试一下固定请求拦截是否生效,我们请求一下路径http://localhost:8080/test2/t?param=123 效果如下图:

ok拦截器没有拦截/test2/**的请求,实验成功

我们来总结一下

  1. 编写HandlerInterceptor继承HandlerInterceptorAdapter实现preHandle方法
  2. 编写拦截器配置继承WebMvcConfigurationSupport实现addInterceptors方法

源码地址 https://gitee.com/wangGet/spring-boot-quick/tree/master/quick-intercprot

转载于:https://my.oschina.net/wangxincj/blog/1862880

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值