返回

十二,SpringBoot-自定义拦截器

发布时间:2022-11-06 11:40:03 345
# java# spring# springboot# java

 springboot自定义拦截器,需要继承WebMvcConfigurerAdapter并重写addInterceptors。

======以下仅为示例,代码沿用上一章=====

具体实现如下:

①创建MyInterceptor.java文件

@Configuration //声明配置
public class MyInterceptor extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor = new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

System.out.println("拦截器启动:"+httpServletRequest.getRequestURL());

return false;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

}
};

//addPathPatterns 需要拦截的路由,excludePathPatterns不需要拦截的路由
registry.addInterceptor(interceptor).addPathPatterns("/**").excludePathPatterns("/login");
}
}

十二,SpringBoot-自定义拦截器_拦截器

其中@Configuration 注解是必须的。

②,启动类中配置@SpringBootApplication。(我的拦截器写在webdev.interceptor下)

十二,SpringBoot-自定义拦截器_ide_02

十二,SpringBoot-自定义拦截器_spring_03

编辑

③,Controller

@RestController
public class WcbDevController {

@RequestMapping("/getPerInfo")
public Object getPerInfo(){
PersonModel personModel = new PersonModel();
personModel.setBirthday(new Date());
personModel.setNickName("不要喷香水");
return personModel;
}

@RequestMapping("/login")
public Object login(){
JSONObject mav = new JSONObject();
mav.put("status",true);
mav.put("msg","登录");
return

十二,SpringBoot-自定义拦截器_拦截器_04

④,启动项目,分别访问查看结果(请自行验证,这里就不截图了!)

 

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线