文档章节

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

Oscarfff
 Oscarfff
发布于 2015/06/09 17:48
字数 1579
阅读 3063
收藏 12
点赞 0
评论 0

如果你的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了。

方案二: 在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"/>


© 著作权归作者所有

共有 人打赏支持
Oscarfff
粉丝 71
博文 804
码字总数 96913
作品 0
崇明
后端工程师
缅甸银河国际开户13170533331

解决这个问题涉及到两个方面的问题: 配置问题 、引入静态文件问题 1、配置问题 web.xml配置的DispatchServlet如下: [html] view plain copy springmvc org.springframework.web.servlet.D...

银河国际 ⋅ 05/26 ⋅ 0

SpringBoot 缓存&资源优化

页面缓存 1. freemarker 的页面静态化 application.properties 配置实现浏览器缓存 这段配置是用来启用资源缓存处理。 借鉴官方文档:https://docs.spring.io/spring-boot/docs/1.5.4.RELEA...

FantJ ⋅ 06/11 ⋅ 0

(一)SpringMVC之配置DispatcherServlet的一些坑

DispatcherServlet是SpringMVC的核心控制器,就像是SpringMVC的心脏,几乎所有的请求都会经过这个控制器,通过它,大大的降低了模块之间的耦合度。所有学SpringMVC的同学们第一步肯定都是先配...

Java攻城玩家 ⋅ 06/03 ⋅ 0

刨根问底:Spring Boot中HandlerInterceptor没有拦截静态资源问题

在Spring Boot中设置了HandlerInterceptor,发现对于js、css等文件都没有起作用。 定义一个HandlerInterceptor 将HandlerInterceptor匹配到所有路径 这时虽然PathPatterns设置了“/**”,但是...

大神带我来搬砖 ⋅ 05/29 ⋅ 0

spring访问静态文件如js,jpg,css

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

五大三粗 ⋅ 2015/09/02 ⋅ 0

SpringBoot--Swagger2配置(解决404报错)

在 spring boot 项目中配置 Swagger2 突然出现了 404 报错, 究其原因,是因为 MVC 没有找到 swagger-ui 包中的 swagger-ui.html 文件; 以下就是 swagger2 的配置,及解决方案: 一, 引入Maven :...

ge洋 ⋅ 05/16 ⋅ 0

5月30日任务 访问日志不记录静态文件、访问日志切割、静态元素过期时间

11.22 访问日志不记录静态文件 ErrorLog "logs/abc.com-error_log" SetEnvIf Request_URI "..gif$" img SetEnvIf Request_URI "..jpg$" img SetEnvIf Request_URI "..png$" img SetEnvIf Req......

吕湘颖 ⋅ 05/14 ⋅ 0

志筛选记录、日志切割、过期时间设置

11.22 访问日志不记录静态文件 网站大多元素为静态文件,如图片、css、js等,这些元素可以不用记录 把虚拟主机配置文件改成如下:在custom上边进行配置 重新加载配置文件 -t, graceful 11.23...

派派菠菜 ⋅ 05/31 ⋅ 0

【2018.05.30学习笔记】【linux基础知识11.22-11.24】

11.22 访问日志不记录静态文件 apache的访问日志会记录网站每个文件被获取的信息,这样日志信息量会很大,我们排查日志的时候不容易筛选有用的记录。我们可以把静态文件的日志设置为不记录,...

lgsxp ⋅ 05/30 ⋅ 0

Spring中拦截/和拦截/*的区别 - 不能访问到返回的JSP - 访问静态资源(jpg,js等)

一、我们都知道在基于Spring的Application中,需要在web.xml中增加下面类似的配置信息: Xml代码 <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </li......

phacks ⋅ 2015/09/13 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

java软件工程师简历中项目经验怎么写?

作者:暗灭 链接:https://www.zhihu.com/question/20695310/answer/180691302 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 直接给你贴个我自己的简历...

颖伙虫 ⋅ 30分钟前 ⋅ 0

Confluence 6 恢复一个站点有关使用站点导出为备份的说明

推荐使用生产备份策略。我们推荐你针对你的生产环境中使用的 Confluence 参考 Production Backup Strategy 页面中的内容进行备份和恢复(这个需要你备份你的数据库和 home 目录)。XML 导出备...

honeymose ⋅ 今天 ⋅ 0

JavaScript零基础入门——(九)JavaScript的函数

JavaScript零基础入门——(九)JavaScript的函数 欢迎回到我们的JavaScript零基础入门,上一节课我们了解了有关JS中数组的相关知识点,不知道大家有没有自己去敲一敲,消化一下?这一节课,...

JandenMa ⋅ 今天 ⋅ 0

火狐浏览器各版本下载及插件httprequest

各版本下载地址:http://ftp.mozilla.org/pub/mozilla.org//firefox/releases/ httprequest插件截至57版本可用

xiaoge2016 ⋅ 今天 ⋅ 0

Docker系列教程28-实战:使用Docker Compose运行ELK

原文:http://www.itmuch.com/docker/28-docker-compose-in-action-elk/,转载请说明出处。 ElasticSearch【存储】 Logtash【日志聚合器】 Kibana【界面】 答案: version: '2'services: ...

周立_ITMuch ⋅ 今天 ⋅ 0

使用快嘉sdkg极速搭建接口模拟系统

在具体项目研发过程中,一旦前后端双方约定好接口,前端和app同事就会希望后台同事可以尽快提供可供对接的接口方便调试,而对后台同事来说定好接口还仅是个开始、设计流程,实现业务逻辑,编...

fastjrun ⋅ 今天 ⋅ 0

PXE/KickStart 无人值守安装

导言 作为中小公司的运维,经常会遇到一些机械式的重复工作,例如:有时公司同时上线几十甚至上百台服务器,而且需要我们在短时间内完成系统安装。 常规的办法有什么? 光盘安装系统 ===> 一...

kangvcar ⋅ 昨天 ⋅ 0

使用Puppeteer撸一个爬虫

Puppeteer是什么 puppeteer是谷歌chrome团队官方开发的一个无界面(Headless)chrome工具。Chrome Headless将成为web应用自动化测试的行业标杆。所以我们很有必要来了解一下它。所谓的无头浏...

小草先森 ⋅ 昨天 ⋅ 0

Java Done Right

* 表示难度较大或理论性较强。 ** 表示难度更大或理论性更强。 【Java语言本身】 基础语法,面向对象,顺序编程,并发编程,网络编程,泛型,注解,lambda(Java8),module(Java9),var(...

风华神使 ⋅ 昨天 ⋅ 0

Linux系统日志

linux 系统日志 /var/log/messages /etc/logrotate.conf 日志切割配置文件 https://my.oschina.net/u/2000675/blog/908189 logrotate 使用详解 dmesg 命令 /var/log/dmesg 日志 last命令,调......

Linux学习笔记 ⋅ 昨天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部