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 标注的方法支持以下参数:
    方法参数 描述
    异常类型 访问引发的异常
    HandlerMethod For access to the controller method that raised the exception.
    WebRequest, NativeWebRequest Generic access to request parameters and request and session attributes without direct use of the Servlet API.
    javax.servlet.ServletRequest, javax.servlet.ServletResponse Choose any specific request or response type (for example, ServletRequest or HttpServletRequest or or Spring’s MultipartRequest or MultipartHttpServletRequest).
    javax.servlet.http.HttpSession Enforces 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.Principal Currently authenticated user — possibly a specific Principal implementation class if known.
    HttpMethod The HTTP method of the request.
    java.util.Locale The current request locale, determined by the most specific LocaleResolver available — in effect, the configured LocaleResolver or LocaleContextResolver.
    java.util.TimeZone, java.time.ZoneId The time zone associated with the current request, as determined by a LocaleContextResolver.
    java.io.OutputStream, java.io.Writer For access to the raw response body, as exposed by the Servlet API.
    java.util.Map, org.springframework.ui.Model, org.springframework.ui.ModelMap For access to the model for an error response. Always empty.
    RedirectAttributes Specify 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.
    @SessionAttribute For 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.
    @RequestAttribute For access to request attributes. See @RequestAttribute for more details.
    Return Values

    @ExceptionHandler methods support the following return values:

    Return value Description
    @ResponseBody The return value is converted through HttpMessageConverter instances and written to the response. See @ResponseBody.
    HttpEntity, ResponseEntity The 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.
    String A 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).
    View A 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.Model Attributes to be added to the implicit model with the view name implicitly determined through a RequestToViewNameTranslator.
    @ModelAttribute An 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 object The view and model attributes to use and, optionally, a response status.
    void A 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 value If 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视图作为错误页。

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章