How does Spring MVC access static files, such as Jpg,js,css?

Source: Internet
Author: User
Tags md5 hash xml example browser cache

If your dispatcherservlet intercepts URLs such as *.do, there is no problem accessing static resources. If your dispatcherservlet intercepts "/", all requests are intercepted, and access to *.js,*.jpg is intercepted.

Purpose: Normal access to static files, do not find static file 404.

Scenario One: Activate Tomcat's defaultservlet to handle static files

XML code

<servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</ url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name> Default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping>

To write in front of the Dispatcherservlet, let Defaultservlet first intercept, this will not enter spring.

Scenario Two: The use of mvc:resources is provided after the spring3.0.4 version:

XML code

<!--access to static resource files-<mvc:resources mapping= "/images/**" location= "/images/"/>

The/images/** maps to Resourcehttprequesthandler for processing, and location specifies the position of the static resource. Can be a Web application root directory, inside the jar package, so that the static resources can be compressed into the jar package. Cache-period can make a static resource for Web cache if the following error occurs, there may be no reason for configuring <mvc:annotation-driven/>. Error warning:no mapping found for HTTP request with URI [/mvc/user/finduser/lisi/770] in Dispatcherservlet with Name ' Spring MVC '

Using the <mvc:resources/> element, the URI of the mapping is registered to the urlmap of simpleurlhandlermapping, and the key is the URI pattern value of mapping. And value is Resourcehttprequesthandler, so that the access to static resources is cleverly transferred from handlermapping to Resourcehttprequesthandler processing and return, Therefore, the Classpath directory is supported, and access to static resources within the jar package is provided. Another thing to note is that do not set DefaultHandler on simpleurlhandlermapping. The static resources request cannot be processed because the defaulthandler of the static URI is Resourcehttprequesthandler.

Scenario three, using <mvc:default-servlet-handler/>

XML code

<mvc:default-servlet-handler/>

The "/**" URL will be registered in the UrlMap of Simpleurlhandlermapping, Transfers access to static resources from handlermapping to Org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler processing and returns DEFAULTSERVLETHTT Prequesthandler, it is the default servlet for each servlet container.

Additional note: The order of execution of multiple handlermapping issues:

The Defaultannotationhandlermapping Order property value is: 0

<mvc:resources/> Auto-registered Simpleurlhandlermapping's Order property value is:2147483646<mvc:default-servlet-handler/> The Simpleurlhandlermapping Order property value for autoenrollment is: 2147483647

Spring executes a smaller order value first. When access to a a.jpg picture file, first through the defaultannotationhandlermapping to find the processor, must not be found, we do not call a.jpg action. And then the order value in ascending, because the last simpleurlhandlermapping is a match "/**", so will definitely match, and then respond to the picture.

Note: If Dispatcherservlet intercepts URLs such as *.do, this problem does not exist.

Plan four, carefully read the source of spring, a good understanding.

17.16.7 Serving of Resources

This option allows the static resource requests following a particular URL pattern to is served by a Resourcehttprequesthan Dler from any of a list of Resource locations. This provides a convenient-serve static resources from locations other than the Web application root, including Loc Ations on the classpath. The cache-period used to set far future expiration headers (1 year is the recommendation of optimization T Ools such as Page speed and YSlow) so that they would be is more efficiently utilized by the client. The handler also properly evaluates the last-modified header (if present) so a 304 status code would be returned as AP Propriate, avoiding unnecessary overhead for resources, is already cached by the client. For example, to serve resource requests with a URL pattern of/resources/** from a public-resources directory within the W EB application Root would use:

@Configuration @enablewebmvcpublic class Webconfig extends Webmvcconfigureradapter {@Override public void ADDRESOURC Ehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresourcelocations ("    /public-resources/"); }}

And the same in XML:

<mvc:resources mapping= "/resources/**" location= "/public-resources/"/>

To serve these resources with a 1-year future expiration to ensure maximum use of the browser cache and a reduction in HTT P requests made by the browser:

@Configuration @enablewebmvcpublic class Webconfig extends Webmvcconfigureradapter {@Override public void ADDRESOURC Ehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresourcelocations ("    /public-resources/"). Setcacheperiod (31556926); }}

And in XML:

<mvc:resources mapping= "/resources/**" location= "/public-resources/" cache-period= "31556926"/>

The mapping attribute must be a Ant pattern that can is used by simpleurlhandlermapping, and the Location attribute Mu St Specify one or more valid resource directory locations. Multiple resource locations may be specified using a comma-separated list of values. The locations specified'll be checked in the specified order for the presence of the resource for any given request. For example, to enable the serving of resources from both the Web application root and from a known path OF/META-INF/PUBL Ic-web-resources/in any jar in the Classpath use:

@EnableWebMvc @configurationpublic class Webconfig extends Webmvcconfigureradapter {@Override public void ADDRESOURC Ehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresou    Rcelocations ("/", "classpath:/meta-inf/public-web-resources/"); }}

And in XML:

<mvc:resources mapping= "/resources/**" location= "/, classpath:/meta-inf/public-web-resources/"/>

When serving resources, then may change, a new version of the application is deployed it's recommended so you Incorp Orate A version string into the mapping pattern used to request the resources so which is the Force clients to request the Newly deployed version of your application ' s resources. Support for versioned URLs are built into the framework and can are enabled by configuring a resource chain on the resource Handler. The chain consists of one more resourceresolver instances followed by one or more resourcetransformer instances. Together they can provide arbitrary resolution and transformation of resources.

The built-in versionresourceresolver can be configured with different strategies. For example a fixedversionstrategy can use a property, a date, or other as the version. A Contentversionstrategy uses A MD5 hash computed from the content of the resource (known as "fingerprinting" URLs).

Contentversionstrategy is a good the default choice to use except in cases where it cannot being used (e.g. with JavaScript Modul E loaders). You can configure different version strategies against different patterns as shown below. Keep in mind also that computing content-based versions are expensive and therefore resource chain caching should be enable D in production.

Java Config example;

@Configuration @enablewebmvcpublic class Webconfig extends Webmvcconfigureradapter {@Override public void ADDRESOURC Ehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresou Rcelocations ("/public-resources/"). Resourcechain (True). Addresolver (New Versionresource    Resolver (). Addcontentversionstrategy ("/**")); }}

XML Example:

<mvc:resources mapping= "/resources/**" location= "/public-resources/" ><MVC:RESOURCE-CHAIN><MVC: Resource-cache/><mvc:resolvers><mvc:version-resolver><mvc:content-version-strategy patterns= " /** "/></mvc:version-resolver></mvc:resolvers></mvc:resource-chain></mvc:resources>

In order for the above to work the application must also render URLs with versions. The easiest-Configure the Resourceurlencodingfilter which wraps the response and overrides its encode URL method. This would work on JSPs, Freemarker, Velocity, and any other view technology that calls the response Encodeurl method. Alternatively, an application can also inject and use directly the Resourceurlprovider beans, which is automatically declar Ed with the Mvc Java Config and the MVC namespace.

17.16.8 falling back in the "Default" Servlet to Serve Resources

This allows-mapping the Dispatcherservlet to "/" (thus overriding the mapping of the container ' s default Servlet), WHI Le still allowing static resource requests to being handled by the container ' s default Servlet. It configures a defaultservlethttprequesthandler with a URL mapping of "/**" and the lowest precedence relative to other URL Mappings.

This handler would forward all requests to the default Servlet. Therefore It is important, it remains last in the order of all and the other URL handlermappings. That'll be is the case if your use <mvc:annotation-driven> or alternatively if you is setting up your own customized Handlermapping instance is sure to set it order property to a value lower than that of the Defaultservlethttprequesthandl Er, which is integer.max_value.

To enable the feature using the default setup use:

@Configuration @enablewebmvcpublic class Webconfig extends Webmvcconfigureradapter {@Override public void configured    Efaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable (); }}

Or in XML:

<mvc:default-servlet-handler/>

The caveat to overriding the '/' servlet mapping is, the RequestDispatcher for the default servlet must be retrieve D by name rather than by path. The Defaultservlethttprequesthandler would attempt to auto-detect the default Servlet for the container at startup time, US ing a list of known names for most of the major Servlet containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, Webl Ogic, and WebSphere). If the default Servlet has been custom configured with a different name, or if a different servlets container is being used Where the default servlet name is unknown and then the default servlet's name must be explicitly provided as in the Followin G Example:

@Configuration @enablewebmvcpublic class Webconfig extends Webmvcconfigureradapter {@Override public void configured    Efaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable ("MyCustomDefaultServlet"); }}

Or in XML:

<mvc:default-servlet-handler default-servlet-name= "Mycustomdefaultservlet"/>


How does Spring MVC access static files, such as Jpg,js,css?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.