我试着用java配置Spring MVC,并且我得到404找不到静态资源,我可以确认其中的文件夹正确地发布到服务器。似乎资源没有得到解决。所以即使调用localhost:8080/SpringMVC/resources/js/jquery-1.4.2.min.js,我也没有找到404。我使用Spring 4.0.1基于Java的配置的Spring MVC - 404找不到静态资源
部署结构
SpringMVC/
resources/
css/
js/
jquery-1.4.2.min.js
WEB-INF/
classes/
lib/
views/
services.jsp
web.xml
我的代码:
COM/ME /配置/ WebApplicationConfig.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.me.services"})
public class WebApplicationConfig extends WebMvcConfigurerAdapter {
private static final String VIEW_RESOLVER_SUFFIX = ".jsp";
private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/views/";
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Bean
public ViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix(VIEW_RESOLVER_PREFIX);
resolver.setSuffix(VIEW_RESOLVER_SUFFIX);
resolver.setViewClass(JstlView.class);
return resolver;
}
}
COM/ME /配置/ Initializer.java
public class Initializer implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_MAPPING = "/";
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebApplicationConfig.class);
rootContext.setServletContext(servletContext);
Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
servlet.addMapping(DISPATCHER_SERVLET_MAPPING);
servlet.setLoadOnStartup(1);
}
}
COM/ME /控制器/ ServicesController.java
@Controller
public class ServicesController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String services(ModelMap model) {
return "services";
}
}
WEB-INF /视图/ services.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<script src="<c:url value="/resources/js/jquery-1.4.2.min.js" />"></script>
</head>
<body>
<h2>Services</h2>
</body>
</html>
GET请求响应调用时本地主机:8080 /用SpringMVC /:
<html>
<head>
<script src="/SpringMVC/resources/js/jquery-1.4.2.min.js"></script>
</head>
<body>
<h2>Services</h2>
</body>
</html>
然后之后404未找到:
localhost:8080/SpringMVC/resources/js/jquery-1.4.2.min.js
您部署的结构有一个名为'jss'的文件夹,您尝试访问的url具有'js'。那可能是问题所在吗? –
对不起,这是我的问题拼写错误 - 现在修复 –
你的意思是这个问题?你的问题解决了吗? –