【发布时间】:2014-05-19 06:50:20
【问题描述】:
我有一个 SpringMVC 项目。在 tomcat7 中运行项目时,我收到以下消息:
No mapping found for HTTP request with URI [/myproject/resources/css/welcome.css] in DispatcherServlet with name 'DispatcherServlet'
CSS 没有被应用:
我尝试了可用的解决方案,但没有一个有效,也没有一个能真正解释发生了什么。
我在/WEB-INF/jsp 中有一个简单的welcome.jsp。这里是:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css"
href="${pageContext.request.contextPath}/resources/css/welcome.css"
rel="stylesheet">
<title>Welcome!</title>
</head>
<body>
<div id="font-HarabaraHand">
<p class="centrify">Poem Collection</p>
</div>
<div id="font-Goodfoot">
<p class="centrify2">What would you like to do?</p>
</div>
</body>
</html>
我的welcome.css 文件位于src/main/webapp/resources/css/。
我的 Spring 配置是基于 java 的,DispatcherServlet 类在 AppInit.java file:
public class AppInit implements WebApplicationInitializer {
// this method is automatically invoked on application startup
public void onStartup(ServletContext container) throws ServletException {
WebApplicationContext webcntx = getWebCntx();
container.addListener(new ContextLoaderListener(webcntx));
ServletRegistration.Dynamic dispatcher = container.addServlet(
"DispatcherServlet", new DispatcherServlet(webcntx));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private AnnotationConfigWebApplicationContext getWebCntx() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebAppConfiguration.class);
return context;
}
}
最后在WebAppConfig.java 文件中:
@Bean
public InternalResourceViewResolver getInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
if (!registry.hasMappingForPattern("/resources/**")) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/").setCachePeriod(CACHE_PERIOD);;
}
}
我的欢迎页面控制器:
@Controller
public class WelcomeController {
@RequestMapping(value="/")
public ModelAndView welcomePage() {
return new ModelAndView("welcome");
}
}
这是我的项目结构:
1.为什么我的welcome.css 文件无法访问?
2。如何更正我的映射配置?
非常感谢有关 Spring url 映射配置的解释或链接。
【问题讨论】:
-
试试
href="${pageContext.request.contextPath}/resources/welcome.css"让我们知道 -
抱歉,您的变体不起作用。我的文件夹结构是
src/main/webapp/resources/css/welcome.css -
然后尝试检查您提供路径的天气是否表明该文件未尝试(f.exits)如果这是真的那么文件正在获取路径
-
不要把你的jsp文件放到WEB-INF里!它们应该在
src/main/webapp文件夹中。 -
@kromit 为什么?我读的正好相反。在 WEB-INF 文件夹中,.jsp 文件不能从客户端访问,而在其他文件夹中它们是。我的项目结构还可以,有很多教程都是一样的,我想可能是我的映射错了。
标签: spring jakarta-ee spring-mvc