SpringMVC and static resources

后端 未结 5 1325
野的像风
野的像风 2020-12-31 14:55

Im new in java and spring. I\'m trying to make hello world app and don\'t get what i\'m doing wrong.

here is my directory structure:

test_app
-pom.xm         


        
相关标签:
5条回答
  • 2020-12-31 15:37

    Use this , it will work always.Good luck :)

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/public-resources/").setCachePeriod(31556926);`enter code here`
        }
    }
    
    0 讨论(0)
  • 2020-12-31 15:37

    I configure the default servlet in web.xml to serve all the static assets, so just route request will reach the controllers:

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/resources/*</url-pattern>
    </servlet-mapping>
    
    0 讨论(0)
  • 2020-12-31 15:52

    Just add both these lines to your dispatcher-servlet.xml

    <mvc:resources mapping="/static/**" location="/static/" />
    <mvc:default-servlet-handler />
    

    Here is what the documentation for default-servlet-handler says:

    Configures a handler for serving static resources by forwarding to the Servlet container's default Servlet. Use of this handler allows using a "/" mapping with the DispatcherServlet while still utilizing the Servlet container to serve static resources. This handler will forward all requests to the default Servlet. Therefore it is important that it remains last in the order of all other URL HandlerMappings. That will be the case if you use the "annotation-driven" element or alternatively if you are setting up your customized HandlerMapping instance be sure to set its "order" property to a value lower than that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.

    0 讨论(0)
  • 2020-12-31 15:54

    It's because of the servlet mapping. All requests coming in are being routed to the servlet. But the servlet doesn't know how to honor the requests for static resources. You need to add a mapping for static resources. There's a few different approaches:

    1. Use the way supplied by the web server. Unfortunately this varies a bit depending on what server you have.

    2. Use a servlet that can serve static resources.

    What web server are you using?

    0 讨论(0)
  • 2020-12-31 15:56

    As of Spring 3.0 and higher you need to add following to your Spring configuration:

    <mvc:resources mapping="/static/**" location="/static/" />
    

    This tells your dispatcher servlet how to resolve static resources. I hope this helps.

    0 讨论(0)
提交回复
热议问题