【发布时间】:2013-06-12 15:22:11
【问题描述】:
我知道以前有人问过类似的问题,但我仍然无法解决这个问题。
我有一个 Spring MVC 网站,其文件树如下所示:
webapp\
resources\
style.css
myimg.png
post.html
Main.html
我的 servlet 将 Main.html 设置为其主页,并使用我使用这些标签提到的样式和图片正确加载:
<link rel="stylesheet" type="text/css" href="resources\style.css"
media="screen" />
<img src="resources\myimg.png" style="padding-left: 25px" />
我也在我的配置中定义(我正在使用类配置):
public class ApiServletConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
当我从Main.html 调用post.html 时,加载的文件没有样式和图像。不知道我还应该做什么才能正确加载它。
post.html 有这些标签:
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<img src="myimg.png" style="padding-left: 25px"/>
另外,我尝试使用 resources\style.css 和 resources\myimg.png
控制器调用如下所示:
@RequestMapping(value = "/{id}/view", method = RequestMethod.GET, produces = "text/html")
public String getPostByIdHtml( @PathVariable String id) throws IOException {
return "/resources/post.html";
}
Main.html 有一个看起来像这样的链接:http://mysite.com/100/view
为了加载 css 和图像,我还应该做什么。 感谢您的帮助!
编辑: 在评论之后,这是我的 web.xml:
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> /Main.html
我猜不是很有趣。我有Java代码的初始化,可能更有趣:
public class WebInit implements WebApplicationInitializer {
@Override
public void onStartup(final ServletContext container) {
final AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ApiServletConfig.class);
final ServletRegistration.Dynamic dispatcher = container.addServlet("api-dispatcher",
new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/api/*");
}
}
【问题讨论】:
-
你能显示你的web.xml吗
-
我编辑了这篇文章。我不在 web.xml 中使用配置,而是使用
WebApplicationInitalizer的实现。它做同样的事情 -
"另外,我尝试使用
resources\style.css和resources\myimg.png"。这是完全错误的。您将其视为本地磁盘文件系统。
标签: java html spring-mvc