首页 > 其他分享 >十三,SpringBoot-全局异常处理器

十三,SpringBoot-全局异常处理器

时间:2022-10-29 20:00:09浏览次数:53  
标签:httpServletRequest Exception SpringBoot Object 处理器 new 全局 public personModel


 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-全局异常处理器_拦截器_02

十三,SpringBoot-全局异常处理器_ide_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 mav;
}

十三,SpringBoot-全局异常处理器_ide_04

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



标签:httpServletRequest,Exception,SpringBoot,Object,处理器,new,全局,public,personModel
From: https://blog.51cto.com/lvyq/5806525

相关文章