【SpringMVC】SpringMVC訪問靜態資源,springmvc訪問靜態

來源:互聯網
上載者:User

【SpringMVC】SpringMVC訪問靜態資源,springmvc訪問靜態

      林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

       本文要以一個例子來說明SpringMVC訪問靜態資源

      <mvc:resources 的使用方法:
<!--對靜態資源檔案的訪問-->

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

下面用一個例子來說明用法

工程免費下載

1、在eclipse中建立一個web工程、

然後匯入如下包:


2、配置web.xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><!--   <welcome-file-list>      <welcome-file>index.html</welcome-file>      <welcome-file>index.htm</welcome-file>      <welcome-file>index.jsp</welcome-file>      <welcome-file>default.html</welcome-file>      <welcome-file>default.htm</welcome-file>      <welcome-file>default.jsp</welcome-file>    </welcome-file-list> --><!-- SpringMVC的前端控制器 --><servlet><servlet-name>MyDispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 載入設定檔路徑 -->  <init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring-servlet.xml</param-value></init-param> <!-- 何時啟動  大於0的值表示容器啟動時初始化此servlet,正值越小優先順序越高-->  <load-on-startup>1</load-on-startup></servlet><!-- Spring MVC設定檔結束 --><!-- SpringMVC攔截設定 --><servlet-mapping><servlet-name>MyDispatcher</servlet-name><!-- 由SpringMVC攔截所有請求 --><url-pattern>/</url-pattern></servlet-mapping><!-- SpringMVC攔截設定結束 --></web-app>

3、然後是控制器:

package com.mucfc;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class StaticFileController {@RequestMapping(value="/image/test")public ModelAndView img(HttpServletRequest request,HttpServletResponse response){  System.out.println("-----img-------");  return new ModelAndView("image");}@RequestMapping(value={"/index","/"})//相對於根目錄的路徑public String test2() {return "index";//指定頁面要跳轉的view視圖路徑}}

4、啟動註解:

<beans xmlns="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="      http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-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/mvc            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd        http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- 把標記了@Controller註解的類轉換為bean --><context:component-scan base-package="com.mucfc"/><!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />    <!-- 靜態資源訪問(不攔截此目錄下的東西的訪問) -->      <mvc:annotation-driven />      <mvc:resources location="/img/"  mapping="/img/**" />    <!-- 對模型視圖名稱的解析,即在模型視圖名稱添加前尾碼 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/WEB-INF/views/" p:suffix=".jsp"/></beans>
5、在WEB-INF建立一個目錄views,並添加一個index.jsp和image.jsp

其中index.jsp:

<%@ page language="java" contentType="text/html; charset=gb2312"    pageEncoding="gb2312"%>    <!-- 這段代碼的意思是擷取當前項目的路徑,如:http://localhost:8080/項目名稱。 -->      <%      String path = request.getContextPath();      String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";      %>   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>  <base href="<%=basePath%>">   <meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>Insert title here</title></head><body>採用String返回視圖: <a href="image/test">訪問圖片</a> </body></html>

和image.jsp如下內容:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <base href="<%=basePath%>"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h>圖片</h><br/><div><img alt="圖片" src="img/Koala.jpg"></div></body></html>

6、在WebContent建立一個目錄,取名img,專門用來存放圖片:

把圖片考進去。

整個工程目錄 如下:



8、接下來就運行了:

可以通過這裡點擊進去看圖片,也可以直接輸入http://localhost:8080/SpringMVCLearningChapter2_1/image/test

工程免費下載

      林炳文Evankaka原創作品。轉載請註明出處http://blog.csdn.net/evankaka

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.