SpringBoot---异常处理、拦截器、跨域

SpringBoot---异常处理、拦截器、跨域,第1张

SpringBoot---异常处理、拦截器、跨域 SpirngBoot—异常处理、拦截器、跨域 前言

异常处理是网站不可避免的,为了用户的体验感,每个完整的网站都有着属于自己的报错页,从而不会展示代码错误给用户看

拦截器的实现很常见,像权限拦截、登陆拦截在很多网站是很常见的~

异常处理 --------------- 普通500异常
@ControllerAdvice
public class SysExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView normal(HttpServletRequest req, HttpServletResponse res,Exception e){
        ModelAndView mv=new ModelAndView();
        mv.setViewName("error/my500");//错误跳转页
        mv.addObject("errormsg",e.getMessage());//传错误信息
        return  mv;
    }
}
--------------- ajax json异常

自定义ajax异常

public class AjaxException extends Exception{

    public AjaxException(String message) {
        super(message);
    }
}

再加入系统异常处理,放在500异常同一个类里

 @ExceptionHandler(value = AjaxException.class)
    @ResponseBody
    public JsonResult ajax(HttpServletRequest req, HttpServletResponse res, Exception e){
        JsonResult json=new JsonResult(500,e.getMessage());
        return  json;
    }
--------------- 404异常

springBoot404异常处理很简单
只需要创建一个error文件夹并且将404页放入其中命名为404.html即可

可简单的进行测试!!!

测试

ajax异常处理

//ajax报错
    @RequestMapping("/ajaxjson")
    @ResponseBody
    public JsonResult ajaxjson(int n) throws AjaxException {
        try {
            int ok=9/n;
        }catch (Exception e){
            throw new AjaxException("ajax查询失败");
        }
        return new JsonResult(200,"ajax查询成功");
    }

运行得到ajax报错后的数据

成功则不进入错误异常

500异常测试也是一样的:

//测试普通报错
    @RequestMapping("/putong")
    public String putong(int n){
        int ok=1/n;
        return "users/index";
    }

只要n不等于0就不会报错
测试结果…
n=0

n!=0

404异常处理
项目中没有该路径即会跳转到404页

拦截器

创建一个拦截器LoginInterceptor
拦截器实现接口 handlerinterceptor

@Component
public class LoginInterceptor implements HandlerInterceptor {
    //拦截前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //检查session 标志 判断是否拦截
        System.out.println("拦截器触发成功...");
        return true;
    }

}

创建一个配置类即可加上注释@Configuration

@Configuration
public class WebConfig implements WebMvcConfigurer {
    //拦截器
    @Autowired
    LoginInterceptor login_lj;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(login_lj)
                .addPathPatterns("/**")
                .excludePathPatterns("/login"); //不拦截的路径
    }
}
跨域

加在配置类中和过滤器一样

//跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //所有网站支持跨域
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS","PATCH")
          //    .allowCredentials(true) //是否允许授权
                .maxAge(3600)
                .allowedHeaders("*");
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5438188.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存