How to handle static content in Spring MVC?

前端 未结 23 2830
春和景丽
春和景丽 2020-11-22 03:28

I am developing a webapp using Spring MVC 3 and have the DispatcherServlet catching all requests to \'/\' like so (web.xml):

  
          


        
23条回答
  •  悲&欢浪女
    2020-11-22 03:55

    Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called (more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.

    In order to use this, use a directory structure that looks like the following:

    src/
     springmvc/
      web/
       MyController.java
    WebContent/
      resources/
       img/
        image.jpg
      WEB-INF/
        jsp/
          index.jsp
        web.xml
        springmvc-servlet.xml
    

    The contents of the files should look like:

    src/springmvc/web/HelloWorldController.java:

    package springmvc.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloWorldController {
    
     @RequestMapping(value="/")
     public String index() {
      return "index";
     }
    }
    

    WebContent/WEB-INF/web.xml:

    
    
    
     
      springmvc
      org.springframework.web.servlet.DispatcherServlet
      1
     
    
     
      springmvc
      /
     
    
    

    WebContent/WEB-INF/springmvc-servlet.xml:

    
    
    
        
     
    
        
     
    
        
     
     
     
    
        
     
      
      
      
     
    
    
    

    WebContent/jsp/index.jsp:

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

    Page with image

    " />

    Hope this helps :-)

提交回复
热议问题