Spring如何编写拦截器呢?
下文笔者讲述Spring中编写拦截器的方法分享,如下所示
Spring拦截器简介
拦截器(Interceptor): 对每一个请求处理前后进行相关的业务处理 Spring拦截器其功能类似于Servlet中的过滤器(Filter)
编写拦截器
package com.java265.interceptor; import org.springframework.stereotype.Component; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 拦截器:计算每一次请求的处理时间 */ @Component public class TestInterceptor extends HandlerInterceptorAdapter { /** * 在请求发生前执行 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { long startTime = System.currentTimeMillis(); System.out.println("拦截器接收到请求的时间:" + new Long(startTime)); request.setAttribute("startTime", startTime); return true; } /** * 在请求发生之后执行 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute("startTime"); request.removeAttribute("startTime"); long endTime = System.currentTimeMillis(); System.out.println("本此请求的处理时间为:" + endTime + " - " + startTime + " = " + new Long(endTime - startTime) + "ms"); request.setAttribute("handlingTime", endTime - startTime); } }
配置类中注册拦截器
package com.java265.interceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration @EnableWebMvc public class MyMvcConfig implements WebMvcConfigurer { TestInterceptor testInterceptor; @Autowired public void setTestInterceptor(TestInterceptor testInterceptor) { this.testInterceptor = testInterceptor; } /** * 注册拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(testInterceptor); } }
控制器
package com.java265.interceptor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/test") public class TestController { @GetMapping("hello") public String sayHello() { return "java265.com"; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。