Spring MVC 静态资源处理

  时间:2018-11-07
本文章向大家介绍Spring MVC 静态资源处理 ,需要的朋友可以参考一下

一、配置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

原文地址:http://www.manongjc.com/article/17693.html