Spring MVC配置靜態資源和資源套件教程

來源:互聯網
上載者:User

標籤:web app   project   func   title   red   input   one   war   load   

1- 介紹這篇教程文章是基於:
  • Spring 4 MVC
2- 建立一個項目
  • File/New/Other..



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


項目被建立以後如下:

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

注意:

Eclipse 4.4(Luna)在建立 Maven 項目結構時可能是有錯誤的。需要修複。
 3- 配置Maven
  • pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  http://maven.apache.org/maven-v4_0_0.xsd">      <modelVersion>4.0.0</modelVersion>  <groupId>com.yiibai</groupId>  <artifactId>SpringMVCResource</artifactId>  <packaging>war</packaging>  <version>0.0.1-SNAPSHOT</version>  <name>SpringMVCResource Maven Webapp</name>  <url>http://maven.apache.org</url>       <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>      </project>
4- 配置Spring 

配置 web.xml

SpringContextListener 將讀取設定檔參數 contextConfigLocation:
  • WEB-INF/web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   version="3.0">    <display-name>Archetype Created Web Application</display-name>   <servlet>       <servlet-name>spring-mvc</servlet-name>       <servlet-class>           org.springframework.web.servlet.DispatcherServlet       </servlet-class>       <load-on-startup>1</load-on-startup>   </servlet>    <servlet-mapping>       <servlet-name>spring-mvc</servlet-name>       <url-pattern>/</url-pattern>   </servlet-mapping>    <!-- Other XML Configuration -->   <!-- Load by Spring ContextLoaderListener -->   <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>          /WEB-INF/root-context.xml        </param-value>           </context-param>     <!-- Spring ContextLoaderListener -->   <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>   </listener> </web-app>
配置Spring MVC:
  • WEB-INF/spring-mvc-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:p="http://www.springframework.org/schema/p"    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-4.1.xsd        http://www.springframework.org/schema/context      http://www.springframework.org/schema/context/spring-context-4.1.xsd        http://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">     <!-- 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></beans>
  • WEB-INF/root-context.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"    xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd">    <!-- Empty --> </beans>
配置靜態資源:
<!-- /WEB-INF/spring-mvc-servlet.xml -->    <!-- Important!! -->   <!-- Default Servlet Handler (For Resources *.css, *.js, image,..) -->   <mvc:default-servlet-handler />   <mvc:annotation-driven />  
資源地圖 <mvc:resources mapping ... >:
 配置Properties檔案:5- Java類

 
  • MyController.java
package com.yiibai.springmvcresource;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic 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):
 
  • ApplicationRB.properties
text.loginPrompt=Enter user name and passwordtext.userName=User Nametext.password=Password
靜態資源
  • 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檔案)
  • staticResourceTest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Spring MVC Resource example</title>  <script type="text/javascript"    src="${pageContext.request.contextPath}/scripts/common.js"></script>          <link rel="stylesheet" type="text/css"    href="${pageContext.request.contextPath}/styles/common.css"> </head><body>     <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!"> </body></html>
  • resourceBundleTest.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Spring MVC Resource Bundle example</title></head><body>    <h2>${appProperties[‘text.loginPrompt‘]}</h2>        ${appProperties[‘text.userName‘]} <input type="text" name="userName"> <br>    ${appProperties[‘text.password‘]} <input type="password" name="password"> <br>          </body></html>
7- 運行應用程式首先,運行應用程式之前,您需要構建整個項目。按右鍵項目並選擇:

回合組態:

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

點擊 Run
靜態資源測試:
  • http://localhost:8080/SpringMVCResource/scripts/common.js
  • http://localhost:8080/SpringMVCResource/styles/common.css
  • http://localhost:8080/SpringMVCResource/staticResourceTest
屬性檔案測試:
    • http://localhost:8080/SpringMVCResource/resourceBundleTest

 

Spring MVC配置靜態資源和資源套件教程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.