此处出现该异常,我的现象是 可以访问controller 中的接口,访问不了 static 目录中的静态资源。
出现的原因是,我项目本身是前后端分离的,因特殊原因做了几个配置界面,配置界面不需要分离部署,总的来说就是为了偷懒,将编译好的资源直接放置到resources/static
中,请求静态资源时,前端显示:
后端异常:
2021-03-15 10:50:50.840 WARN 24628 --- [.0-11018-exec-3] o.s.web.servlet.PageNotFound : No mapping for GET /index.html
2021-03-15 10:50:50.841 ERROR 24628 --- [.0-11018-exec-3] c.l.c.exception.GlobalExceptionHandler : http://127.0.0.1:11018/index.html
2021-03-15 10:50:50.842 ERROR 24628 --- [.0-11018-exec-3] c.l.c.exception.GlobalExceptionHandler : E1001
org.springframework.web.servlet.NoHandlerFoundException: No handler found for GET /index.html
at org.springframework.web.servlet.DispatcherServlet.noHandlerFound(DispatcherServlet.java:1255) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1018) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) [spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) [spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635) [bes-lite-spring-boot-2.x-starter-9.5.2.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) [spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742) [bes-lite-spring-boot-2.x-starter-9.5.2.jar:na]
at com.bes.enterprise.webtier.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [bes-lite-spring-boot-2.x-starter-9.5.2.jar:na]
at com.bes.enterprise.webtier.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [bes-lite-spring-boot-2.x-starter-9.5.2.jar:na]
at cloud.lesscode.crud.filter.CharacterFilter.doFilter(CharacterFilter.java:79) [lesscode-core-crud-2.0.2.jar:2.0.2]
at com.bes.enterprise.webtier.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [bes-lite-spring-boot-2.x-starter-9.5.2.jar:na]
此处应该是配置问题,一般springboot项目,默认可以访问静态,但是添加如下配置:
spring.mvc.static-path-pattern=/static/**
并没有暖用,看样子还有其他地方有配置问题,只好用原始方式解决了,添加启动注解,设置静态资源,方法如下:
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer{
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
}
OK,解决了,至于为什么这么写,参考此处:SpringBoot—WebMvcConfigurer详解