路径访问相关配置
spring.mvc.throw-exception-if-no-handler-found【没有Handler就抛异常】【默认false】
当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中。
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关系是啥
根据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:/
最佳实践
#启动ResourceHttpRequestHandler
spring.resources.add-mappings=true
#设置ResourceHttpRequestHandler的作用范围
spring.mvc.static-path-pattern=/resources/**
spring.resources.static-locations=file:/opt/x/y/z/static/
#如果没有找到Handler就报错(除去ResourceHttpRequestHandler的作用范围)
spring.mvc.throw-exception-if-no-handler-found: true
解决@ControllerAdvice不能捕获404的问题
spring.mvc.throw-exception-if-no-handler-found: true
开启开关,找不到Handler就抛异常NoHandlerFoundException
默认spring.mvc.static-path-pattern=/,拦截所有路径,所以就不存在NoHandlerFound情况。需要为静态资源指定路径:**
spring.mvc.static-path-pattern=/resources/**
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String processMethodNotSupportedException(Exception exception) {
exception.printStackTrace();
return "error";
}
}