Spring MVC与基于Java的配置 - 404找不到静态资源

时间:2014-02-25 11:37:14

标签: java spring spring-mvc

我正在尝试使用java配置的Spring MVC,而且我找不到404静态资源,我可以确认的文件夹最终被发布到服务器。似乎资源根本没有得到解决。所以即使调用localhost:8080 / SpringMVC / resources / js / jquery-1.4.2.min.js我也找不到404。我正在使用Spring 4.0.1

部署结构

SpringMVC/
   resources/
      css/
      js/
         jquery-1.4.2.min.js  
   WEB-INF/
      classes/
      lib/
      views/ 
         services.jsp
      web.xml

我的代码:

COM /我/配置/ 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 /我/配置/ 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>

调用localhost时的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 Not Found on:

之后
localhost:8080/SpringMVC/resources/js/jquery-1.4.2.min.js

1 个答案:

答案 0 :(得分:6)

我认为在您的services.jsp中,您可以尝试使用单引号:

<script src="<c:url value='/resources/js/jquery-1.4.2.min.js' />"></script>

<script>中有两组双引号似乎是一个问题。