Spring MVC配置靜態資源和資源包教程

1- 介紹

這篇教程文章是基於:

  • Spring 4 MVC

2- 創建一個項目

  • File/New/Other..

Spring
Spring
Spring
輸入:

  • Group ID: com.yiibai
  • Artifact ID: SpringMVCResource
  • Package: com.yiibai.springmvcresource

Spring
項目被創建以後如下:

Spring
不要擔心有錯誤消息在項目被創建時。原因是,我們還沒有聲明 Servlet 庫。

注意:

Eclipse 4.4(Luna)在創建 Maven 項目結構時可能是有錯誤的。需要修復。
Spring

3- 配置Maven

  • pom.xml

4.0.0
com.yiibai
SpringMVCResource
war
0.0.1-SNAPSHOT
SpringMVCResource Maven Webapp
http://maven.apache.org

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>


    <!-- Servlet API -->
    <!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>


    <!-- Jstl for jsp page -->
    <!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>


    <!-- JSP API -->
    <!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
        <scope>provided</scope>
    </dependency>



    <!-- Spring dependencies -->
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

    <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>

</dependencies>

<build>
    <finalName>SpringMVCResource</finalName>
    <plugins>

        <!-- Config: Maven Tomcat Plugin -->
        <!-- http://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin -->
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>

            <!-- Config: contextPath and Port (Default - /SpringMVCResource : 8080) -->

            <!--
            <configuration>
                <path>/</path>
                <port>8899</port>
            </configuration>
            -->
        </plugin>
    </plugins>
</build>

4- 配置Spring

配置 web.xml

SpringContextListener 將讀取配置文件參數 contextConfigLocation:
Spring

  • WEB-INF/web.xml

Archetype Created Web Application

spring-mvc

org.springframework.web.servlet.DispatcherServlet

1

spring-mvc / contextConfigLocation /WEB-INF/root-context.xml org.springframework.web.context.ContextLoaderListener

配置Spring MVC:

  • WEB-INF/spring-mvc-servlet.xml

<!-- Package Scan -->
<context:component-scan base-package="com.yiibai.springmvcresource" />

<!-- Enables the Spring MVC Annotation Configuration -->
<context:annotation-config />

<!-- Important!! -->
<!-- Default Servlet Handler (For Resources \*.css, \*.js, image,..) -->
<mvc:default-servlet-handler />
   <mvc:annotation-driven />    

<!-- Config resource mapping -->
<mvc:resources mapping="/styles/\*\*" location="/WEB-INF/resources/css/" />


<!-- Config Properties file -->
<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list><value>classpath:ApplicationRB.properties</value></list>
    </property>
</bean>

<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">

    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>

    <property name="suffix">
        <value>.jsp</value>
    </property>

    <property name="exposedContextBeanNames">
        <list><value>appProperties</value></list>
    </property>
</bean>
  • WEB-INF/root-context.xml

配置靜態資源:

<mvc:default-servlet-handler />
<mvc:annotation-driven />

資源映射 <mvc:resources mapping ... >:
Spring

配置Properties文件:

5- Java類

Java類

  • MyController.java

package com.yiibai.springmvcresource;

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

@Controller
public class MyController {

@RequestMapping(value = "/staticResourceTest")
public String staticResource(Model model) {
    return "staticResourceTest";
}

@RequestMapping(value = "/resourceBundleTest")
public String resourceBundle(Model model) {
    return "resourceBundleTest";
}

}

6- 資源包,靜態資源和視圖

Resource Bundle (Properties file):

Spring

  • ApplicationRB.properties

text.loginPrompt=Enter user name and password
text.userName=User Name
text.password=Password

靜態資源
Spring

  • scripts/common.js

function sayHello() {
alert("Hello from JavaScript");
}

  • /WEB-INF/resource/css/commons.css

.button {
font-size: 20px;
background: #ccc;
}

.red-text {
color: red;
font-size: 30px;
}

.green-text {
color: green;
font-size: 20px;
}

視圖(兩個JSP文件)

Spring

  • staticResourceTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

Spring MVC Resource example
<div class="red-text">Red text</div>
<br>
<div class="green-text">Green text</div>
<br>

<input type="button" class="button" onclick="sayHello();"
    value="Click me!">
  • resourceBundleTest.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>

Spring MVC Resource Bundle example

${appProperties\['text.loginPrompt'\]}

${appProperties\['text.userName'\]} <input type="text" name="userName"> <br>
${appProperties\['text.password'\]} <input type="password" name="password"> <br>

7- 運行應用程序

首先,運行應用程序之前,您需要構建整個項目。

右鍵單擊項目並選擇:
Spring
Spring

運行配置:

Spring
Spring
輸入:

  • Name: Run SpringMVCResource
  • Base directory: ${workspace_loc:/SpringMVCResource} 可選擇「Browse Workspace..." 來選對應項目。
  • Goals: tomcat7:run

Spring
點擊 Run
Spring

靜態資源測試:

屬性文件測試:

代碼下載: http://pan.baidu.com/s/1dDSnUcL