Spring MVC 的拦截器(Interceptor)与 Java Servlet 的过滤器(Filter)类似,它主要用于拦截用户的请求并做相应的处理,通常应用在权限验证、记录请求信息的日志、判断用户是否登录等功能上。
一、创建Maven项目
参考:SpringBoot第 1 讲:HelloWorld_秦毅翔的专栏-CSDN博客
二、修改pom.xml
<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>
<!-- SpringBoot支持01、parent:Begin -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<!-- SpringBoot支持01、parent:End -->
<groupId>org.personal.qin.demos</groupId>
<artifactId>rest_demo</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- java版本 -->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- SpringBoot:Begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot:End -->
<!-- SpringMVC:Begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- SpringMVC:End -->
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- 资源文件拷贝插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- SpringBoot支持03、添加SpringBoot的插件支持:Begin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- SpringBoot支持03、添加SpringBoot的插件支持:End -->
</plugins>
</build>
</project>
三、自定义RestController 3.1、Rest请求方式
Rest有4中常用HttpRequest请求方式,分别与数据库的增、删、改、查相对应 RequestMapping 数据库操作
@PostMapping insert
@DeleteMapping delete
@PutMapping update
@GetMapping select
3.2、@PathVariable注解的使用
@PathVariable注解用于接收请求路径中的占位符
比如:
@PostMapping("/{username}/{password}")
public String login(@PathVariable String username, @PathVariable String password) {
...
}
浏览器发送请求:
http://127.0.0.1:8080/admin/123456 3.3、实例:TestRestController.java
package demo.rest.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import demo.rest.entity.HttpResult;
@RestController
@RequestMapping("rest")
public class TestRestController {
/**
* 增
* @param id
* @return
*/
@PostMapping("/{id}")
public HttpResult testPost(@PathVariable String id) { // @PathVariable接收请求路径中的占位符
return new HttpResult(200, "添加数据", id);
}
/**
* 删
* @param id
* @return
*/
@DeleteMapping("/{id}")
public HttpResult testDelete(@PathVariable String id) { // @PathVariable接收请求路径中的占位符
return new HttpResult(200, "删除数据", id);
}
/**
* 改
* @param id
* @return
*/
@PutMapping("/{id}")
public HttpResult testPut(@PathVariable String id) { // @PathVariable接收请求路径中的占位符
return new HttpResult(200, "修改数据", id);
}
/**
* 查
* @param id
* @return
*/
@GetMapping("/{id}")
public HttpResult testGet(@PathVariable String id) { // @PathVariable接收请求路径中的占位符
return new HttpResult(200, "查询数据", id);
}
}
四、自定义拦截器(非必须)
package demo.rest.interceptors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import demo.rest.utils.Log;
/**
* SpringMVC中的拦截器,可以添加多个拦截器
*/
@Configuration
public class TestInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor handlerInterceptor = new HandlerInterceptor() {
/**
* 在请求Controller之前被执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Log.i(getClass(), "*******preHandle");
// String name = request.getParameter("name");
// if("admin".equals(name)) {
// return true;
// } else {
// return false;
// }
return true;
}
/**
* 在请求Controller完成之后被执行
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
Log.i(getClass(), "*******postHandle");
}
/**
* 在请求完成后被执行(只有当preHandle的返回值为true时被执行)
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
Log.i(getClass(), "*******afterCompletion");
}
};
registry.addInterceptor(handlerInterceptor); // 添加拦截器
}
}
五、启动BootApplication
package demo.rest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestBootApplication {
public static void main(String[] args) {
SpringApplication.run(RestBootApplication.class, args);
}
}