Development of Web application based on Spring MVC (III.)-Resources

Source: Internet
Author: User
Tags browser cache

Web application development based on spring MVC (3)-Resources

The previous article describes how spring MVC handles resource files by adding logs to a spring MVC-based Web project.

Note that the dispatcherservlet of the Web. XML configuration for this project corresponds to the Url-pattern "/", that is, all URL requests are processed by spring MVC. The actual Web project has a lot of resource files, such as JavaScript files, CSS files, png,jpg and other picture files, even flash, etc., we do not need to access these static files to set the corresponding URL, which will result in a lot of repetitive labor, as well as maintenance complexity. Spring MVC provides a mechanism to map a URL and a location that is followed by a static file that corresponds to a static file in the location directory. This configuration is:

<resources mapping= "/resources/**" location= "/resources/"/>

Explain that

1. Access, browser display webapp/resources/test.png

2. Access, browser display webapp/resources/scripts/test.js

3. Access, browser display WEBAPP/RESOURCES/CSS/2012/TEST.CSS

Note that the value of mapping "/resources/**" has two *, which represents all URLs under the map resources/, including sub-paths (that is, multiple/), such as 1, 2, 3 above, if there is only one *, only the 1-level path can be mapped, that is, only access 1, Access 2, 3 will be an error.

Unfortunately, if you add only this line, the @requestmapping map with the @controller class will not take effect. I am the search to StackOverflow on this post Lenovo to the solution, and later in StackOverflow found another post there is a more detailed explanation, the post said that the use of <mvc:resources/> must be added <mvc: Annotation-driven/>, and then the @requestmapping mapping information with the @controller annotation class can be read to.

Now Servlet-context.xml is:

< XML version= "1.0" encoding= "UTF-8" ><beans:beans xmlns= "" xmlns:xsi= "" xmlns:beans= "" xmlns:context= "" xmlns : mvc= "" xsi:schemalocation= "Rg/schema/beans pringframework.org/schema/context/spring-context-3.1.xsd" ><!-- Dispatcherservlet Context:defines This servlet ' s request-processing infrastructure--><!--Handles HTTP GET reques TS for/resources/** by efficiently serving up static resources in the ${webapproot}/resources/directory--><resour Ces mapping= "/resources/**" location= "/resources/"/><!--Imports user-defined @Controller beans that process Client requests--><beans:import resource= "Controllers.xml"/><!--you has to add the because you had a < Resources/> Declare--><mvc:annotation-driven/></beans:beans>

Access, the content of the test.js is exactly what is displayed on the browser.

The following resolves a problem left in HelloWorld's article, in which @RequestMapping there is only one "/simple", but found from the log, there are three kinds of URLs "/simple", "/simple.*", "/simple/" Mapping

info:org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping-mapped URL Path [/simple] onto Handler ' Simplecontroller ' INFO:org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping- Mapped URL Path [/simple.*] onto handler ' Simplecontroller ' INFO: org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping-mapped URL Path [/simple/] onto Handler ' Simplecontroller '

Look at defaultannotationhandlermapping, this class has a Usedefaultsuffixpattern member variable, which defaults to true, which is the 3 URL variant that identifies a URL by default. In the Addurlsforpath method, if the IF condition is established (usedefaultsuffixpattern=true), the other two mappings ("/simple.*", "/simple/") are added,

So access to http://localhost:8080/web/simple/, even (the invented suffix), is actually equivalent to the URL of http://localhost:8080/web/simple.

After dealing with the legacy of HelloWorld, it is natural to see how the startup log is mapped after the <mvc:resources/> has been added:

Info:org.springframeworthod.annotation.requestmappinghandlermapping-mapped "{[/simple],methods=[],params=[], Headers=[],consumes=[],produces=[],custom=[]} "onto public java.lang.String Org.springframework.samples.mvc.simple.SimpleController.simple ()

is no longer defaultannotationhandlermapping, and replaced by Requestmappinghandlermapping.

Let's change our mind and see how SPRINGMVC handles the three URLs mentioned above from the request side.

Visit http://localhost:8080/web/simple

Debug:org.springframeworthod.annotation.requestmappinghandlermapping-looking up handler method for Path/simpletrace : Org.springframeworthod.annotation.requestmappinghandlermapping-found 1 Matching mapping (s) for [/simple]: [{[/ Simple],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}]

Access

Debug:org.springframeworthod.annotation.requestmappinghandlermapping-looking up handler method for path/ Simple.htmltrace:org.springframeworthod.annotation.requestmappinghandlermapping-found 1 Matching mapping (s) for: [{[ /simple.*],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}]

Access (invented suffix name)

Debug:org.springframeworthod.annotation.requestmappinghandlermapping-looking up handler method for path/ Simple.footrace:org.springframeworthod.annotation.requestmappinghandlermapping-found 1 Matching mapping (s) for [/ Simple.foo]: [{[/simple.*],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}]

It's amazing that SPRINGMVC automatically identifies three URLs, how does it all work? The boot log obviously only mapped a URL.

Still want to see the source code of Requestmappinghandlermapping, there are two attributes Usesuffixpatternmatch and Usetrailingslashmatch,

Usesuffixpatternmatch (using suffix pattern matching) is true by default, which means that "/simple.*" can be identified,

Usetrailingslashmatch (trailing slash match) defaults to true, meaning "/simple/" can be identified.

Finally, notice that the class of two boot log printing is not the same

The front one is defaultannotationhandlermapping, the latter one is requestmappinghandlermapping, and this is why?

The reason for this is that the Spring factory has changed the bean selection after joining <mvc:resources/>

Before <mvc:resouces/>, SPRINGMVC used the default policy, so defaultannotationhandlermapping was used,

After adding <mvc:resources/>, Springmvc no longer uses the default policy, but instead uses the Requestmappinghandlermapping class, which should be written in the source code.

====================================================================

[Supplementary note, not to look, translation is also very slag]spring Reference Document (Spring official manual) 16.14.5 configuraing serving of resources in this section of the resources introduction:

This configuration (<mvc:resources/>) configures the resource location for Resourcehttprequesthandler so that handler can handle the static resource request for a particular URL pattern. It provides a convenient way to access static resources directly from the physical path, including the root path of the Web application and the path on the classpath. The Cache-period property can be used to set up experimental headers that might be used in the future (perhaps a year from now, which depends on the power of the optimization tools such as page speed and YSlow), which makes it more efficient for clients to use. This handler also properly evaluates the header of the last-modified (if any), so the 304 status code (HTTP status code, as we often know the 404 wrong translator returned on the browser) will be properly returned, to avoid the server that has been cached by the client again. , causing the load. For example, to use a URL pattern like/resources/** to request access to a server resource under the root internal public-resources directory of a Web application, you can use:

@EnableWebMvc @configurationpublic class Webconfig extends Webmvcconfigureradapter {@Override public void Addresourcehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresourcelocations ("/public-resources/"); }}

The same configuration in XML is in:

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

The following configuration of the processing resources satisfies the experimental characteristics of the year just mentioned, ensuring maximum usage of the browser cache and reducing browser-initiated HTTP requests:

@EnableWebMvc @configurationpublic class Webconfig extends Webmvcconfigureradapter {@Override public void Addresourcehandlers (Resourcehandlerregistry Registry) {Registry.addresourcehandler ("/resources/**"). Addresourcelocations ("/public-resources/"). Setcacheperiod (31556926); }}

Also in XML:

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

Mapping this attribute must be an ant pattern (not very clear what an ant mode translator is), the ant pattern can be used by simplehandlermapping, and the Location property must specify one or more valid resource directory locations. Multiple resource locations can be specified by using a comma delimiter list value. The specified location will be checked again in a specific order based on the performance of any given request resource. For example, to enable us to access the Web application root path and to access a known/meta-inf/public-web-resources/path in any jar package under the classpath path, we write:

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

In the XML:

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

When resources are likely to change with the release of a new version of the application, it is recommended that you put a version string in the mapping mode used when requesting the resource, so you can force the client to request a new version of the deployment in the application resource. Such a version string is configured with Spel, so it can be easily managed in a single place when a new version is deployed.

For example, we consider an application that uses a component of a performance-optimized, custom Dojo JavaScript library in a production environment that is typically deployed under a/public-resources/dojo/dojo.js path in a Web application. Because different parts of dojo may be merged into a custom artifact for each new version of the app, the client browser will need to re-download the custom Artifact Dojo.js resource forcefully, as long as a new version of the application is deployed. A simple way to pack is to manage the version of your app in a. Properties profile, such as:

application.version=1.0.0

Then use the <util:properties/> tag in a bean to allow the values in the properties file to be accessed by Spel:

<util:properties id= "Applicationprops" location= "/web-inf/spring/application.properties"/>

Now it's accessible through spel,application.version, and we can merge it into the <resource/> tab.

<mvc:resources mapping= "/resources-#{applicationprops[' application.version ']}/**" location= "/public-resources /"/>

In the Java class, you can use the @propertiessource annotation and then inject the environment abstract class to access all the predefined property values:

@EnableWebMvc @configuration@propertysource ("/web-inf/spring/application.properties") public class Webconfig Extends Webmvcconfigureradapter {@Inject environment env; @Override public void Addresourcehandlers ( Resourcehandlerregistry registry) {Registry.addresourcehandler ("/resources-" + env.getproperty (" Application.Version ") +"/** "). Addresourcelocations ("/public-resources/"); }}

Finally, in order to request resources using the appropriate URL, we can take advantage of the Spring JSP tag: (translator used in JSP pages)

<spring:eval expression= "@applicationProps [' application.version ']" var= "Applicationversion"/><spring: URL value= "/resources-{applicationversion}" var= "ResourceUrl" > <spring:param name= "applicationversion" value= "${applicationversion}"/></spring:url><script src= "${resourceurl}/dojo/dojo.js" type= "text/ JavaScript > </script>

Article answer
    • This question title: Web application development based on Spring MVC (III.)-Resources
    • This question address: http://www.educity.cn/wenda/117654.html

Development of Web application based on Spring MVC (III.)-Resources

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.