1. 程式人生 > >Spring MVC 靜態資源處理 (三)

Spring MVC 靜態資源處理 (三)

完整的專案案例: springmvc.zip

目錄

例項

專案結構:

 

一、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"> <!-- 配置請求總控器 --> <servlet> <servlet-name>dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</
param-name> <param-value>classpath:dispatcher-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping
> </web-app>
View Code

二、配置dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="edu.nf.ch03.controller"/>

    <mvc:annotation-driven/>

    <!-- 靜態資源的處理 -->
    <!-- 方式一:將靜態頁面等資源交由給servlet容器來處理,Springmvc不參與解析-->
    <!-- 任何的servlet容器都有一個DefaultServlet來處理靜態資源-->
    <!--<mvc:default-servlet-handler/>-->

    <!-- 方式二:靜態資源由springmvc自己來處理-->
    <!-- mapping用於對映靜態資源的url,location用於指定靜態資源的本地相對路徑-->
    <!-- 意思就是將mapping對映的請求url到location指定的相應目錄中查詢靜態資源,
         location實行可以同時指定多個目錄,中間用逗號隔開-->
    <mvc:resources mapping="/page/**" location="/static/,/assesst/"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

三、controller類:

package edu.nf.ch03.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author wangl
 * @date 2018/10/29
 */
@Controller
public class TestController {

    @GetMapping("/test")
    public ModelAndView test(){
        System.out.println("test...");
        return new ModelAndView("index");
    }
}
View Code

四、請求靜態資源: