嗨我有简单的Spring应用程序:
WebConfig.java:
package spittr.web;
@Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
}
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
registerForm.jsp:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="sf" %>
<%@ page session="false" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Spittr</title>
<link rel="stylesheet" type="text/css"
href="<c:url value="/resources/style.css" />" >
</head>
<body>
<h1>registration</h1>
<sf:form method="POST" commandName="spitter" >
<sf:errors path="*" element="div" cssClass="errors" />
<sf:label path="firstName"
cssErrorClass="error">name</sf:label>:
<sf:input path="firstName" cssErrorClass="error" /><br/>
....
<input type="submit" value="register" />
</sf:form>
</body>
</html>
当我在以上注册表格中获取:
@RequestMapping(value="/register", method=GET)
public String showRegistrationForm(Model model) {
model.addAttribute("spitter", new Spitter());
return "registerForm";
}
CSS文件没有加载,我得到JSP页面,但没有CSS样式,并且在Tomcat控制台中有错误:
127.0.0.1 - - [22 / Nov / 2016:18:04:48 +0100]“GET /Spittr-0.0.1-SNAPSHOT/resources/style.css HTTP / 1.1”405 1045
问题出在哪里? CSS文件位于 /Spittr-0.0.1-SNAPSHOT/resources/style.css 路径中,并且我指定了默认资源处理程序,因此为什么JSP页面无法获取此静态文件。
感谢您的任何建议:)
答案 0 :(得分:1)
好的,我明白了:
1-从 WebMvcConfigurationSupport
重写 resourceHandlerMapping()@Override
@Bean
public HandlerMapping resourceHandlerMapping() {
AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) super.resourceHandlerMapping();
handlerMapping.setOrder(-1);
return handlerMapping;
}
2 - 从 WebMvcConfigurationSupport / WebMvcConfigurerAdapter 覆盖 addResourceHandlers():
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}