SpringMVC訪問靜態資源


  1、如果只配置攔截類似於*.do格式的url,則對靜態資源的訪問是沒有問題的,如下:

<!-- SpringMVC核心分發器 -->
    <servlet> 
        <servlet-name>dispatcherServlet</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param> 
            <param-name>contextConfigLocation</param-name> 
            <param-value>classpath*:config/dispatcher-servlet.xml</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <!-- 映射*.do的請求 -->
    <servlet-mapping> 
        <servlet-name>dispatcherServlet</servlet-name> 
        <url-pattern>*.do</url-pattern> 
    </servlet-mapping> 

  2、如果配置攔截了所有的請求,如下:

<!-- SpringMVC核心分發器 -->
    <servlet> 
        <servlet-name>dispatcherServlet</servlet-name> 
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param> 
            <param-name>contextConfigLocation</param-name> 
            <param-value>classpath*:config/dispatcher-servlet.xml</param-value> 
        </init-param> 
        <load-on-startup>1</load-on-startup> 
    </servlet> 
    <!-- 映射所有的請求 -->
    <servlet-mapping> 
        <servlet-name>dispatcherServlet</servlet-name> 
        <url-pattern>/</url-pattern> 
    </servlet-mapping> 

  這樣的配置,會造成js文件、css文件、圖片文件等靜態資源無法訪問。

    1)以圖片為例子,將一張a.png的圖片存放到web項目根目錄下的/img目錄中。

    2)在jsp頁面中訪問這張圖片

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
        訪問圖片靜態資源:<br>
        <div>
            <img alt="圖片資源" src="../img/a.png">
        </div>
</body>
</html>

    3)通過Controller訪問這個jsp

package cn.luxh.app.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="/res")
public class StaticResourceAccessController {
    
    @RequestMapping(value="/staticRes")
    public String accessRes() {
        System.out.println("訪問靜態資源");
        return "getStaticRes";
    }
}

    4)訪問結果如下:

    可以看到圖片無法訪問。

    5)SpringMVC提供了<mvc:resources />標簽來處理這個問題,在SpringMVC的配置文件dispatcher-servlet.xml中做如下配置:

        <!-- 靜態資源訪問 -->
        <!-- 類似於:/img/** 的url請求的資源都到/img/目錄下查找  -->
        <mvc:resources location="/img/" mapping="/img/**"/>

    6)配置好之后,重新訪問,OK。

  3、為了方便,可以把js文件、css文件、圖片文件統一放到resource目錄下的各自子目錄中,如/resource/js、/resource/css/resource/img。然后做一個統一配置就可以了。

 

<!-- 靜態資源訪問 -->
<mvc:resources location="/resource/**" mapping="/resource/**"/>

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM