zoukankan      html  css  js  c++  java
  • SpringMVC REST 风格静态资源访问配置

    1 在web.xml中使用默认servlet处理静态资源,缺点是如果静态资源过多,则配置量会比较大,一旦有遗漏,则会造成资源无法正常显示或404错误。

    <!-- 静态资源访问控制 -->
        <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>*.jpg</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>*.png</url-pattern>
        </servlet-mapping>
        <!-- rest风格的拦截,需进行静态资源访问配置 -->
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>

    2 在springmvc配置文件中配置

    我的所有静态资源都在WebContent/static/之下,下有如下目录WebContent/static/img,WebContent/static/css,WebContent/static/js等等,在springmvc配置文件中添加如下配置,以下两个配置二选一即可,当然配置两最小的是第二种了,第一种的优势在于可以自主定制,可以规定哪些静态资源是可以访问的,哪些是不能访问的。

    <!--静态资源的访问配置,文件夹配置,二选一 -->
    <mvc:resources mapping="/static/**" location="/static/" cache-period="31556926"/>
    <!--静态资源的访问配置,文件夹配置,二选一 -->
    <mvc:default-servlet-handler/>

    FAQ:

    如果在配置文件中无法使用<mvc:相关的标签,可能是你未引入xmlns:mvc="http://www.springframework.org/schema/mvc"命名空间,其次spring版本3.0以上,我的是3.0.5版本的,测试可行。

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/aop    
                http://www.springframework.org/schema/aop/spring-aop-3.0.xsd    
                http://www.springframework.org/schema/beans    
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
                http://www.springframework.org/schema/context    
                http://www.springframework.org/schema/context/spring-context-3.0.xsd    
                http://www.springframework.org/schema/mvc    
                http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    
                http://www.springframework.org/schema/tx    
                http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
  • 相关阅读:
    CLR via C#
    一些写英文简历的词汇
    组合与组合数
    A lowlevel Look at the ASP.NET Architecture
    \r与\n的区别,\r\n与\n或\r的区别(C语言/C#)
    Canvas lineWidth 属性 【每日一段代码18】
    程序员三大世界观 如何看待HTML5
    Canvas运用样式与颜色fillStyle【每日一段代码15】
    Canvas绘制路径:贝塞尔曲线【每日一段代码12】
    Canvas绘制弧形【每日一段代码10】
  • 原文地址:https://www.cnblogs.com/daxin/p/3876569.html
Copyright © 2011-2022 走看看