所以我正在尝试使用Spring MVC设置一个简单的应用程序,我无法将CSS应用于页面。
首先,这是我的配置。我正在使用基于Java的配置。
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/site/views/");
res.setSuffix(".html");
return res;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/site/**").addResourceLocations("classpath:/site/");
};
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(DispatcherConfig.class);
dispatcherContext.register(ServiceConfig.class);
Dynamic dispatcher = container.addServlet("dispatcher",
new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
我的html / css / js资源被组织成这样的文件夹:
我的控制器看起来像这样:
@Autowired
private CatService catServiceImpl;
@RequestMapping("/")
public String index(Model model) {
return "index";
}
@RequestMapping("/cat/{cat}")
public String cat(@PathVariable String cat, Model model) {
final List<Dog> animals = catServiceImpl.getData(Data.valueOf(cat));
model.addAttribute("animals ", animals );
return "animals_list";
}
}
最后,我将css导入html,如下所示:
<link rel="stylesheet" type="text/css" href="site/css/index.css">
<link rel="stylesheet" type="text/css" href="site/css/animals_list.css">
现在问题在于:
当我加载索引页面时,我得到一个正常的结果。应用了CSS,一切正常。但是,当我在索引页面上使用链接并进入返回animals_list页面的控制器时,我得到的页面很好,但CSS没有应用。我只收到内容。 部署animals_list.css(100%,检查它)。 对我来说令人费解的是,为什么它在索引页面上有效,而在animals_list页面上却没有。两者都由ViewResolver解析,并以相同的方式导入样式表。 我错过了什么?