`

Spring MVC如何访问到静态的文件,如jpg,js,css,png,gif?

 
阅读更多

如果你的DispatcherServlet拦截 *.do这样的URL,就不存在访问不到静态资源的问题。如果你的DispatcherServlet拦截“/”,拦截了所有的请求,同时对*.js,*.jpg的访问也就被拦截了。

目的:可以正常访问静态文件,不要找不到静态文件报404。

 

 
方案一:激活Tomcat的defaultServlet来处理静态文件

 

Xml代码

<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>

要写在DispatcherServlet的前面, 让 defaultServlet先拦截,这个就不会进入Spring了,我想性能是最好的吧

Tomcat, Jetty, JBoss, and GlassFish 自带的默认Servlet的名字 -- "default"

Google App Engine 自带的 默认Servlet的名字 -- "_ah_default"
Resin            自带的 默认Servlet的名字 -- "resin-file"
WebLogic     自带的 默认Servlet的名字  -- "FileServlet"
WebSphere  自带的 默认Servlet的名字 -- "SimpleFileServlet" 

 

方案二: 在spring3.0.4以后版本提供了mvc:resources 的使用方法

 

Xml代码

 <!-- 对静态资源文件的访问 -->
 <mvc:resources mapping="/images/**" location="/images/" />

/images/**映射到ResourceHttpRequestHandler进行处理,location指定静态资源的位置.可以是web application根目录下、jar包里面,这样可以把静态资源压缩到jar包中。cache-period 可以使得静态资源进行web cache 如果出现下面的错误,可能是没有配置<mvc:annotation-driven />的原因。 报错WARNING: No mapping found for HTTP request with URI [/mvc/user/findUser/lisi/770] in DispatcherServlet with name 'springMVC'

使用<mvc:resources/>元素,把mapping的URI注册到SimpleUrlHandlerMapping的urlMap中,key为mapping的URI pattern值,而value为ResourceHttpRequestHandler,这样就巧妙的把对静态资源的访问由HandlerMapping转到ResourceHttpRequestHandler处理并返回,所以就支持classpath目录,jar包内静态资源的访问.另外需要注意的一点是,不要对SimpleUrlHandlerMapping设置defaultHandler。因为对static uri的defaultHandler就是ResourceHttpRequestHandler,否则无法处理static resources request。

 

 

方案三: 使用<mvc:default-servlet-handler/>

 

Xml代码

 <mvc:default-servlet-handler/>

会把"/**" url,注册到SimpleUrlHandlerMapping的urlMap中,把对静态资源的访问由HandlerMapping转到org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler处理并返回DefaultServletHttpRequestHandler使用,就是各个Servlet容器自己的默认Servlet。

补充说明:多个HandlerMapping的执行顺序问题:

DefaultAnnotationHandlerMapping的order属性值是:0

<mvc:resources/ >自动注册的SimpleUrlHandlerMapping的order属性值是:2147483646
<mvc:default-servlet-handler/>自动注册的SimpleUrlHandlerMapping的order属性值是:2147483647

spring会先执行order值比较小的。当访问一个a.jpg图片文件时,先通过DefaultAnnotationHandlerMapping来找处理器,一定是找不到的,我们没有叫a.jpg的Action。再按order值升序找,由于最后一个SimpleUrlHandlerMapping是匹配"/**"的,所以一定会匹配上,再响应图片。

注:如果DispatcherServlet拦截 *.do这样的URL,就不存上述问题了。

 

 

方案四:认真阅读spring的源码,好好理解一下。

 

17.16.7 Serving of Resources

This option allows static resource requests following a particular URL pattern to be served by a ResourceHttpRequestHandler from any of a list of Resource locations. This provides a convenient way to serve static resources from locations other than the web application root, including locations on the classpath. The cache-period property may be used to set far future expiration headers (1 year is the recommendation of optimization tools such as Page Speed and YSlow) so that they will be more efficiently utilized by the client. The handler also properly evaluates the Last-Modified header (if present) so that a 304 status code will be returned as appropriate, avoiding unnecessary overhead for resources that are already cached by the client. For example, to serve resource requests with a URL pattern of /resources/** from a public-resources directory within the web application root you would use:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(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 HTTP requests made by the browser:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(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 an Ant pattern that can be used by SimpleUrlHandlerMapping, and the location attribute must specify one or more valid resource directory locations. Multiple resource locations may be specified using a comma-separated list of values. The locations specified will 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/public-web-resources/ in any jar on the classpath use:

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/""classpath:/META-INF/public-web-resources/");
    }
}

And in XML:

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

When serving resources that may change when a new version of the application is deployed it is recommended that you incorporate a version string into the mapping pattern used to request the resources so that you may force clients to request the newly deployed version of your application’s resources. Support for versioned URLs is built into the framework and can be 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 an MD5 hash computed from the content of the resource (known as "fingerprinting" URLs).

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

Java config example;

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/public-resources/")
                .resourceChain(true).addResolver(
                    new VersionResourceResolver().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 way to do that is to configure the ResourceUrlEncodingFilter which wraps the response and overrides its encodeURL method. This will work in 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 bean, which is automatically declared with the MVC Java config and the MVC namespace.

17.16.8 Falling Back On the "Default" Servlet To Serve Resources

This allows for mapping the DispatcherServlet to "/" (thus overriding the mapping of the container’s default Servlet), while still allowing static resource requests to be handled by the container’s default Servlet. It configures a DefaultServletHttpRequestHandler with a URL mapping of "/**" and the lowest priority relative to other URL mappings.

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 <mvc:annotation-driven> or alternatively if you are setting up your own customized HandlerMapping instance be sure to set its order property to a value lower than that of the DefaultServletHttpRequestHandler, which is Integer.MAX_VALUE.

To enable the feature using the default setup use:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

Or in XML:

<mvc:default-servlet-handler/>

The caveat to overriding the "/" Servlet mapping is that the RequestDispatcher for the default Servlet must be retrieved by name rather than by path. The DefaultServletHttpRequestHandler will attempt to auto-detect the default Servlet for the container at startup time, using a list of known names for most of the major Servlet containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere). If the default Servlet has been custom configured with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then the default Servlet’s name must be explicitly provided as in the following example:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable("myCustomDefaultServlet");
    }
}

Or in XML:

<mvc:default-servlet-handler default-servlet-name="myCustomDefaultServlet"/>
分享到:
评论

相关推荐

    Spring MVC入门教程

    七、spring mvc 如何访问到静态的文件,如jpg,js,css? 八、spring mvc 请求如何映射到具体的Action中的方法? 九、spring mvc 中的拦截器: 十、spring mvc 如何使用拦截器? 十一、spring mvc 如何实现全局的异常...

    Spring MVC 教程 快速入门 深入分析

    七、spring mvc 如何访问到静态的文件,如jpg,js,css? 八、spring mvc 请求如何映射到具体的Action中的方法? 九、spring mvc 中的拦截器: 十、spring mvc 如何使用拦截器? 十一、spring mvc 如何实现全局的异常...

    精通Spring MVC 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Spring MVC 教程快速入门 深入分析

    七、Spring MVC如何访问到静态的文件:描述了如何配置Spring MVC来处理静态资源,如图片、JavaScript和CSS文件等。 八、Spring MVC请求如何映射到具体的Action中的方法:说明了如何配置映射器(HandlerMapping)将...

    Spring MVC jar包

    Spring MVC 是一个基于Java的轻量级Web应用框架,它为开发者提供了模型-视图-控制器(MVC)架构,使开发人员能够更好地组织和分离应用程序的业务逻辑、数据处理和用户界面。Spring MVC是Spring框架的一个核心组件,...

    springMVC3学习(四)--访问静态文件如js,jpg,css(源码)

    springMVC3学习(四)--访问静态文件如js,jpg,css(源码) 文章地址:http://blog.csdn.net/itmyhome1990/article/details/25987411

    Spring MVC 文件上传下载 后端 - Java.zip

    5. **错误处理**:在开发过程中,可能会遇到各种错误,如文件过大、格式不支持、存储失败等。因此,为这些错误编写合适的异常处理逻辑是必要的,可以提供友好的错误提示并记录日志。 6. **优化**:为了提高性能,...

    spring mvc文件上传实现进度条

    这个场景通常涉及到前端的JavaScript或jQuery库(如jQuery File Upload)与后端的Spring MVC控制器之间的交互,以及可能的多线程处理来跟踪文件上传的进度。接下来,我们将深入探讨如何在Spring MVC中实现这一功能。...

    Spring MVC和springboot静态资源处理.rar

    静态资源通常包括HTML、CSS、JavaScript、图片等文件,是构成Web应用程序用户体验的重要部分。本篇文章将详细讲解Spring MVC和Spring Boot如何处理这些资源。 ### Spring MVC 静态资源处理 Spring MVC作为Spring...

    如何访问到静态的文件,如jpg,js,css..docx

    ### 如何有效访问静态文件(如jpg, js, css):多方案解析 #### 背景介绍 在Web开发中,经常会遇到如何正确配置服务器以便能够顺利访问静态资源(如图片、JavaScript脚本、CSS样式表等)的问题。本文将详细介绍几种...

    基于Spring MVC的Web应用设计源码

    文件类型包括587个PNG图片文件、423个CSS样式文件、73个Java源代码文件、49个JavaScript脚本文件、32个GIF图片文件、29个JSP页面文件、17个XML配置文件、7个CHM帮助文件、3个Properties配置文件和3个JPG图片文件。...

    Spring+Spring MVC+Spring JDBC+MySql实现简单登录注册

    在本项目中,我们主要利用Spring框架,包括其核心模块Spring、MVC模块Spring MVC以及数据访问/集成模块Spring JDBC,结合MySQL数据库来构建一个基础的登录注册系统。以下是这个项目涉及的关键技术点: 1. **Spring...

    spring mvc json&&jackson jquery js

    Spring MVC中的`@ResponseBody`注解可以将方法的返回值直接转换为JSON格式发送到客户端,而`@RequestBody`则可以将请求体中的JSON数据解析成Java对象。 **Jackson** Jackson是Java中广泛使用的JSON库,它可以高效地...

    Spring MVC使用Demo

    这通常包括安装Java Development Kit (JDK)、配置IDE(如IntelliJ IDEA或Eclipse)、添加Spring MVC的相关依赖到构建工具(如Maven或Gradle)的pom.xml或build.gradle文件中。还需要配置Web应用服务器,比如Tomcat,...

    基本的spring mvc + spring security实现的登录(无数据库)

    - 通常包含src/main/java目录下的Controller、Service、DAO层以及配置类,src/main/resources下可能有Spring MVC和Spring Security的配置文件,webapp下是静态资源和视图文件。 7. **学习重点**: - 理解Spring ...

    spring mvc上传 下载ftp文件

    spring mvc上传 下载ftp文件

    Spring mvc 教程

    - **Web 安全**:Spring MVC 提供了安全相关的功能,如认证和授权。 #### “约定优于配置”支持 (Convention over Configuration) - **控制器类名-处理器映射 ControllerClassNameHandlerMapping**:自动将控制器...

    spring mvc+spring+maven框架项目,纯净项目

    4. **src/main/webapp**: Web应用目录,包含静态资源(如HTML、CSS、JavaScript)、WEB-INF下的web.xml(Web应用部署描述符)以及Spring MVC的视图解析路径。 5. **src/test**: 测试代码目录,使用JUnit进行单元测试...

    spring mvc

    #### 七、Spring MVC 如何访问静态文件 在 Spring MVC 中,可以通过配置 `&lt;mvc:resources&gt;` 标签来指定静态资源的映射路径。例如: ```xml &lt;mvc:resources mapping="/static/**" location="/WEB-INF/static/" /&gt; ``...

    spring mvc restful service

    6. **配置Spring MVC**:在`DispatcherServlet`的配置文件(如`web.xml`)中,我们需要配置`DispatcherServlet`,并指向Spring MVC的配置文件。在Spring MVC配置文件中,我们需要设置视图解析器、映射处理器、数据...

Global site tag (gtag.js) - Google Analytics