springboot2-spingmvc相关支持

@ControllerAdvice

我们知道@ExceptionHandler注解可以注解到某个@Controller类的方法上,作为当前类的统一异常处理方法;如果我们想把这个异常处理方法作用于全局,那么就需要用到@ControllerAdvice注解,具体使用步骤如下:

@ControllerAdvice+@ExceptionHandler 实现全局异常配置
  1. 第一步自定义一个异常处理类,并标注 @ControllerAdice注解
  2. 第二步定义一个异常处理方法 并标注@ExceptionHandler
@ControllerAdvice
public class GlobleExceptionHandler {
    /**
     *功能描述
     * @author qqg
     * @date
     * @param
     * @return
    */
    @ExceptionHandler(GlobleException.class)
    public void uploadException(GlobleException ex, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write("上传文件大小超出限制");
        printWriter.flush();
        printWriter.close();
    }
    
    /**
     *功能描述
     * @author qqg
     * @date
     * @param
     * @return 方法可以有返回值,可以是一个json ,一个视图名等
    */

    @ExceptionHandler(Exception.class)
    public ModelAndView customException(Exception ex){
        ModelAndView mv = new ModelAndView();
        mv.addObject("mag","数据获取失败");
        mv.setViewName("error");
        return mv;
    }

}

说明:
  1. @ControllerAdvice注解

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface ControllerAdvice {
        @AliasFor("basePackages")
        String[] value() default {};
    
        @AliasFor("value")
        String[] basePackages() default {};
    
        Class<?>[] basePackageClasses() default {};
    
        Class<?>[] assignableTypes() default {};
    
        Class<? extends Annotation>[] annotations() default {};
    }
    
    
// 指定作用在所有标注@RestController的类
@ControllerAdvice(annotations = RestController.class)
public class ExampleAdvice1 {}

// 指定作用在指定的包的类
@ControllerAdvice("org.example.controllers")
public class ExampleAdvice2 {}

// 指定在特殊的controller上
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})
public class ExampleAdvice3 {}
  1. @ExceptionHandler注解

    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface ExceptionHandler {
        Class<? extends Throwable>[] value() default {};
    }
    
    1. @ExceptionHandler 标注的方法支持以下参数:
    方法参数描述
    异常类型访问引发的异常
    HandlerMethodFor access to the controller method that raised the exception.
    WebRequest, NativeWebRequestGeneric access to request parameters and request and session attributes without direct use of the Servlet API.
    javax.servlet.ServletRequest, javax.servlet.ServletResponseChoose any specific request or response type (for example, ServletRequest or HttpServletRequest or or Spring’s MultipartRequest or MultipartHttpServletRequest).
    javax.servlet.http.HttpSessionEnforces the presence of a session. As a consequence, such an argument is never null. Note that session access is not thread-safe. Consider setting the RequestMappingHandlerAdapter instance’s synchronizeOnSession flag to true if multiple requests are allowed to access a session concurrently.
    java.security.PrincipalCurrently authenticated user — possibly a specific Principal implementation class if known.
    HttpMethodThe HTTP method of the request.
    java.util.LocaleThe current request locale, determined by the most specific LocaleResolver available — in effect, the configured LocaleResolver or LocaleContextResolver.
    java.util.TimeZone, java.time.ZoneIdThe time zone associated with the current request, as determined by a LocaleContextResolver.
    java.io.OutputStream, java.io.WriterFor access to the raw response body, as exposed by the Servlet API.
    java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMapFor access to the model for an error response. Always empty.
    RedirectAttributesSpecify attributes to use in case of a redirect — (that is to be appended to the query string) and flash attributes to be stored temporarily until the request after the redirect. See Redirect Attributes and Flash Attributes.
    @SessionAttributeFor access to any session attribute, in contrast to model attributes stored in the session as a result of a class-level @SessionAttributes declaration. See @SessionAttribute for more details.
    @RequestAttributeFor access to request attributes. See @RequestAttribute for more details.
    Return Values

    @ExceptionHandler methods support the following return values:

    Return valueDescription
    @ResponseBodyThe return value is converted through HttpMessageConverter instances and written to the response. See @ResponseBody.
    HttpEntity, ResponseEntityThe return value specifies that the full response (including the HTTP headers and the body) be converted through HttpMessageConverter instances and written to the response. See ResponseEntity.
    StringA view name to be resolved with ViewResolver implementations and used together with the implicit model — determined through command objects and @ModelAttribute methods. The handler method can also programmatically enrich the model by declaring a Model argument (described earlier).
    ViewA View instance to use for rendering together with the implicit model — determined through command objects and @ModelAttribute methods. The handler method may also programmatically enrich the model by declaring a Model argument (descried earlier).
    java.util.Map, org.springframework.ui.ModelAttributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator.
    @ModelAttributeAn attribute to be added to the model with the view name implicitly determined through a RequestToViewNameTranslator.Note that @ModelAttribute is optional. See “Any other return value” at the end of this table.
    ModelAndView objectThe view and model attributes to use and, optionally, a response status.
    voidA method with a void return type (or null return value) is considered to have fully handled the response if it also has a ServletResponse an OutputStream argument, or a @ResponseStatus annotation. The same is also true if the controller has made a positive ETag or lastModified timestamp check (see Controllers for details).If none of the above is true, a void return type can also indicate “no response body” for REST controllers or default view name selection for HTML controllers.
    Any other return valueIf a return value is not matched to any of the above and is not a simple type (as determined by BeanUtils#isSimpleProperty), by default, it is treated as a model attribute to be added to the model. If it is a simple type, it remains unresolved.

拦截器配置

  1. 自定义拦截器处理逻辑 实现HandlerInterceptor接口

    public class CustormInterceptor implements HandlerInterceptor {
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    
            System.out.println("拦截器处理逻辑.......");
            return true;
        }
    }
    
  2. 注册拦截器类,实现WebMvcConfigurer

    @Configuration
    public class InterceptorConfig implements WebMvcConfigurer {
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new CustormInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns("/index");
    
        }
    }
    
    

错误页的配置

@ControllerAdvice定义的处理机制一般用来处理应用级别的异常,对于容器级别的错误还有另外一种形式;

springboot错误默认是由BasicErrorController类来处理的,该类源码:

    static {
        Map<Series, String> views = new EnumMap(Series.class);
        views.put(Series.CLIENT_ERROR, "4xx");
        views.put(Series.SERVER_ERROR, "5xx");
        SERIES_VIEWS = Collections.unmodifiableMap(views);
    }

private ModelAndView resolve(String viewName, Map<String, Object> model) {
        String errorViewName = "error/" + viewName;
        TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
        return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
    }

如上可知:springboot默认会在error目录找4xx,5xx的文件作为错误视图,找不到会使用error视图作为错误页。

简单的建立如下目录:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值