2016-09-23 204 views
0

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

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

所以Tomcat的记录器显示正确的映射到资源

映射的URL路径[/资源/ **]到类型[类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>

它应该显示为正在运行的片段。B如我所说,该应用程序无法找到并加载资源。

Log File

classpath

enter image description here

enter image description here

任何帮助吗?

+0

把你的日志来调试或跟踪,告诉我们Spring吐出了什么。 –

+0

完成,检查我的编辑。 @SotiriosDelimanolis –

+0

那些日志显示_Successfully completed request_。 –

回答

1

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

你缺少web应用程序名称:

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

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

使用春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" %> 
+0

我正在使用Thymeleaf和.html文件来查看视图,我怎样才能在这些文件中引用taglib? 当我按照您指出的方式使用导入时,我在浏览器检查器中看到以下错误:2http:// localhost:8080 /%3Cspring:url%20value =%22/resources/css/MyCss.css%22 /% 3E无法加载资源:服务器响应的状态为404 –

+0

我对Thymeleaf并不熟悉,但从wiki中我看到它是基于servlet的,而JSP文件基本上是Servlet文件,它在Tomcat的Jasper组件转换成servlet后。你想把这个taglib作为一个指令添加到一个JSP文件中。 –