How to serve static content in spring mvc?

2019-02-21 02:03发布

问题:

I am using spring-mvc framework in my current project. ROOT folder has lots of web folders containing html, jsp, css, js etc. My spring mvc configuration is as follows:

<context:annotation-config />

    <bean id="comicControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.ComicController" />
    <bean id="dashboardControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.DashBoardController" />
    <bean id="genericControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.GenericController" />
    <bean id="channelControllerBean" class="tv.cinemacraft.videogramwebapp.springmvc.controllers.ChannelController" />

    <!-- <context:component-scan base-package="tv.cinemacraft.videogramwebapp.springmvc.controllers" /> -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="1" />
    </bean>

    <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
        <property name="basename" value="views" />
        <property name="order" value="0" />
    </bean>

And I have mapping defined in my java controller. But this is causing static content like any image to vanish. If I request for any image inside any folder by accessing ROOT//.jpg, it gives me 404 response code although image exists. If I remove spring-mvc, image gets displayed.

Note that spring-mvc's resources attribute works for static content but that need my static content to be present inside particular folder e.g. resouce folder. So this approach is not useful for me.

回答1:

Let’s say you have a directory (/resources/my_images/) that contains some product images, and you want to serve these images upon request. For example, if the requested URL is http://localhost:8080/ mystore/resource/my_images/P123.png, then you would like to serve the image with the P123.png name. Similarly, if the requested URL is http://localhost:8080/mystore/resource/images/P1234.png, then an image with the name P1234.png needs to be served.

Now how you can serve static images with Spring MVC?

  1. Place some images under the src/main/webapp/resources/my_images/ directory;
  2. Add the following tag in our web application context’s configuration DispatcherServlet-context.xml file: <mvc:resources location="/resources/" mapping="/resource/**"/>
  3. run your application and enter http://localhost:8080/mystore/resource/images/P123.png (change the image name in the URL based on the images you placed

FYI: <mvc:resources> tag in the web application context configuration to tell Spring where these image files are located in our project so that spring can serve those files upon request.