不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2021-12-12 23:25:37  修改时间:2024-03-27 05:43:09  分类:Java框架/系统  编辑

第一步:在application.yml文件中添加如下两句:

#没有绑定的url直接抛出错误
spring.mvc.throw-exception-if-no-handler-found=true
#不为静态文件建立映射
spring.web.resources.add-mappings=false

第二步:自定义一个异常处理类AllExceptionHandler

@RestControllerAdvice
public class AllExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(AllExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public Msg defaultErrorHandler(Exception e) {
        logger.error("AllExceptionHandler ", e);

        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            //404 Not Found
            return new Msg(404, e.getMessage());
        } else {
            //500
            return new Msg(500, e.getMessage());
        }
    }
}

自定义的Msg类:

public class Msg {

    /**
     * 返回码
     */
    private int resultCode;

    /**
     * 备注信息
     */
    private String info;

    /**
     * 空构造函数
     */
    public Msg() {
    }

    /**
     * 自定义消息
     *
     * @param resultCode resultCode
     * @param info       info
     */
    public Msg(int resultCode, String info) {
        this.resultCode = resultCode;
        this.info = info;
    }

   ...

}

解决swagger前端资源(js/css/img),不能正常访问的问题

当设置了spring.web.resources.add-mappings=false时,前端静态资源(如:js/css/img)加载失败,解决方案如下:

在实现WebMvcConfigurer这个接口的类中加入下面的方法实现

@Configuration
public class MyWebMvcConfigurerAdapter implements WebMvcConfigurer {
    /**
     * 配置静态访问资源
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/", "/static", "/public");
 
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

 

Spring Boot配置接口 WebMvcConfigurer

SpringBoot——》WebMvcConfigurerAdapter详解

Springboot2(5)WebMvcConfigurer讲解

SpringBoot-WebMvcConfigurer详解