路径访问相关配置

spring.mvc.throw-exception-if-no-handler-found【没有Handler就抛异常】【默认false】

解决@ControllerAdvice不能捕获404的问题 - 图1
当HandlerMapping没有找到handler时

  • 如果配置了throw-exception-if-no-handler-found抛出异常交给ExceptionResolver处理
  • 没有配置就设置response状态,这样就交给tomcat处理了。(tomcat redirect到/error,然后springboot自定义有/error的Handler处理)

    spring.resources.add-mappings【添加mapping】【默认true】

    spring.resources.add-mappings=ture注册ResourceHttpRequestHandler,如果有了
    Handler,就不会执行到noHandlerFound中。
    image.png
    static-path-pattern默认是/拦截所有路径**

    spring.mvc.static-path-pattern【mapping路径】【默认是/**

    可以通过配置spring.mvc.static-path-pattern=/resources/来设定ResourceHttpRequestHandler**的作用范围。

    spring.resources.static-locations【资源路径】

    和spring.mvc.static-path-pattern关系是啥
    image.png
    根据static-path-pattern获取到Handler(ResourceHttpRequestHandler),handler从static-locations中获取静态资源。

    “spring.mvc.static-path-pattern”用于阐述HTTP请求地址,而“spring.resources.static-locations”则用于描述静态资源的存放位置。

static-locations默认值:
默认为classpath:[/META-INF/resources/,/resources/, /static/, /public/]以及context:/
image.png

最佳实践

  1. #启动ResourceHttpRequestHandler
  2. spring.resources.add-mappings=true
  3. #设置ResourceHttpRequestHandler的作用范围
  4. spring.mvc.static-path-pattern=/resources/**
  5. spring.resources.static-locations=file:/opt/x/y/z/static/
  6. #如果没有找到Handler就报错(除去ResourceHttpRequestHandler的作用范围)
  7. spring.mvc.throw-exception-if-no-handler-found: true

或通过代码设置
image.png

解决@ControllerAdvice不能捕获404的问题

  1. spring.mvc.throw-exception-if-no-handler-found: true

开启开关,找不到Handler就抛异常NoHandlerFoundException
默认spring.mvc.static-path-pattern=/,拦截所有路径,所以就不存在NoHandlerFound情况。需要为静态资源指定路径:**

  1. spring.mvc.static-path-pattern=/resources/**
  1. @ControllerAdvice
  2. public class ControllerExceptionHandler {
  3. @ExceptionHandler(NoHandlerFoundException.class)
  4. @ResponseStatus(HttpStatus.BAD_REQUEST)
  5. public String processMethodNotSupportedException(Exception exception) {
  6. exception.printStackTrace();
  7. return "error";
  8. }
  9. }