Spring MVC无法提供静态资源

时间:2016-09-23 19:56:51

标签: java spring spring-mvc

我试图提供静态资源(css文件)。 我已经注册了位置和处理程序

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

因此Tomcat的Logger显示正确的资源映射

  

将映射的URL路径[/ resources / **]映射到[class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]类型的处理程序

当浏览器呈现视图时,检查器会在尝试获取静态资源时显示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 preffix 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>
&#13;
&#13;
&#13;

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

Log File

classpath

enter image description here

enter image description here

任何帮助?

1 个答案:

答案 0 :(得分:1)

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

您缺少网络名称:

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

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

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

以下是我如何导入bootstrap.min.css:

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

不要忘记添加taglib,如下所示:

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