java - Spring MVC 无法提供静态资源

标签 java spring spring-mvc

我正在尝试提供静态资源(css 文件)。

我已经注册了位置和处理程序

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
    }
}

这样 Tomcat 的记录器就会显示到资源的正确映射

Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

当浏览器渲染 View 时,检查器会在尝试获取静态资源时显示 404 错误。

enter image description here

AppInitializer.java

@Configuration
@ComponentScan("com.learning")
@EnableWebMvc
public class ApplicationInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer {

    private final Logger LOGGER = Logger.getLogger(ApplicationInitializer.class.getName());
    public static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    @Autowired
    private ApplicationContext applicationContext;

    public ApplicationInitializer() {
    }

    //region Context Initialization Area
    public void onStartup(ServletContext servletContext) throws ServletException {
        WebApplicationContext springContext = getSpringApplicationContext();
        MyDispatcherServlet dispatcherServlet = new MyDispatcherServlet(springContext);

        servletContext.addListener(new ContextLoaderListener(springContext));
        servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
        servletContext.getSessionCookieConfig().setHttpOnly(true);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, dispatcherServlet);
        dispatcher.addMapping("/");
        dispatcher.setLoadOnStartup(1);

    }

    private WebApplicationContext getSpringApplicationContext() {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        LOGGER.info(String.format("Registering springApplicationContext: %s", context));
        // Loads into container first
        context.register(ApplicationInitializer.class);
        LOGGER.info(String.format("Registration success of springApplicationContext: %s", context));
        return context;
    }
    //endregion

    //region ViewResolver Region
    @Bean
    public ViewResolver viewResolver() {
        //Runs after coontroller ends its execution. It receives the view name to be processed.
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        resolver.setCharacterEncoding("UTF-8");
        return resolver;
    }

    @Bean
    public TemplateEngine templateEngine() {
        // Processes the template
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setEnableSpringELCompiler(true);
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        //Resolves templates with provided prefix and suffix
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
    //endregion

    //region ResourceHandler Region
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
    }
    //endregion
}

Hello.html

h1 {
    color: red;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="/resources/css/MyCss.css" th:href="@{/resources/css/MyCss.css}"/>
</head>
<body>
    <h1 th:text="'Hello ' + ${name}">Hello World</h1>
</body>
</html>

它应该显示为正在运行的代码片段...但正如我提到的,应用程序无法找到并加载资源。

Log File

classpath

enter image description here

enter image description here

有什么帮助吗?

最佳答案

http://localhost:8080/resources/css/MyCss.css

您缺少网络应用程序名称:

http://localhost:8080/webapp_name/resources/css/MyCss.css

在您的:link rel="stylesheet"...

使用Spring URL标记,以便更好地解析您的URL。

这是我用来导入 bootstrap.min.css 的方法:

<link rel="stylesheet" href='<spring:url value="/resources/bootstrap/bootstrap.min.css"/>' type="text/css" />

不要忘记添加标签库,如下所示:

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

关于java - Spring MVC 无法提供静态资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39668626/

相关文章:

java - iText 是否创建基于图像或基于文本的 PDF 文件?

java - 如何使用 equals 方法将对象添加到数组列表中以排除相似的对象?

JavaFX 新场景或新 Pane

spring-mvc - 在 Spring 打开一个弹出窗口

java - 简单的CRUD操作异常设计

java - Spring MVC 中的 StreamingOutput 等价物

Spring Boot 未从 YML 文件加载属性

java - 如何使用泛型在抽象类中注入(inject)服务

Spring @ControllerAdvice 与 ErrorController

spring - 需要帮助为 Spring Security CAS 客户端创建 "successful authentication"页面