Spring Boot拦截器实现步骤及测试实例

网友投稿 383 2023-06-15

Spring Boot-实现步骤及测试实例

Spring Boot-实现步骤及测试实例

第一步,定义-:

package com.zl.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class myInterceptor implements HandlerInterceptor {

@Override

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

System.out.println("preHandle");

return true;

}

@Override

public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

System.out.println("preHandle");

}

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

System.out.println("preHandle");

}

}

控制台打印三个输出语句,作为测试。

第二步:配置-

package com.zl.interceptor;

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;

@Configuration

public class WebMVCConfig implements WebMvcConfigurer {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(myInterceptor()).addPathPatterns("/**");

}

@Bean

myInterceptor myInterceptor(){

return new myInterceptor();

}

}

将定义的-注入到这个配置方法中,并拦截所有路径。

第三步:写个接口测试

package com.zl.interceptor;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@Rhttp://estController

public class helloController {

@GetMapping("/hello")

public String hello(){

return "hello";

}

}

测试结果

定义的-三个方法都执行了。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Boot如何使用AOP实例解析
下一篇:Spring Boot Redis客户端远程操作实现过程解析
相关文章

 发表评论

暂时没有评论,来抢沙发吧~