Spring4 MVC HelloWord範例


Spring4 MVC入門教學

本教學是基於以下工具寫的:
  • MyEclipse 10
  • Spring 4.0.3.RELEASE

2- 預覽應用程式執行流程

Spring MVC DispatcherServlet 讀取 xml 組態檔案的原則:
  • {servlet-name} ==> /WEB-INF/{servlet-name}-servlet.xml

如果你不想用 SpringMVC 使用原則,可以重新組態 SpringMVC  DispatcherServlet 在 web.xml 檔案中:
<servlet>
   <servlet-name>my-dispatcher-name</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <init-param>
       <!-- override default name {servlet-name}-servlet.xml -->
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/springmvc-myconfig.xml</param-value>
   </init-param>
   <load-on-startup>1</load-on-startup>
</servlet>
應用程式的流程:

3 - 建立Maven工程

建立Maven專案型別。 Maven是幫助我們管理庫的最好方式。
在 Eclipse, 選擇 "File/New/Other..."


選擇 archetype "maven-archetype-webapp"。

輸入:
  • Group Id: com.yiibai
  • Artifact Id: HelloSpringMVC
  • Package: com.yiibai.springmvc

這樣將建立專案,結構如下圖所示:

不要擔心專案在建立的時候出現錯誤資訊。原因是,現在我們還沒有宣告 Servlet 庫。
在 Eclipse 中建立 Maven 專案結構可能是錯誤的。需要我們去檢查出來並完善。

4- 組態Spring

這是專案建成後的檔案結構圖:

組態 Maven 使用 Spring 庫.
  • pom.xml
<projectxmlns="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>HelloSpringMVC</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>HelloSpringMVC 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 Library -->
        <!-- 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>
 
        <!-- 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>HelloSpringMVC</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 - /HelloSpringMVC : 8080) -->
                <!--
                <configuration>
                    <path>/</path>
                    <port>8899</port>
                </configuration>
                -->   
            </plugin>
        </plugins>
    </build>   
     
</project>
組態 web.xml:
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
    
   <display-name>HelloWorldSpring</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 的 DispatcherServlet將根據原則讀取XML組態檔案:
  • {servlet-name} ==> /WEB-INF/{servlet-name}-servlet.xml

  • 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">
 
   <context:component-scan base-package="com.yiibai.tutorial.springmvc"/>
    
   <context:annotation-config/>
    
   <bean
       class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
       <property name="prefix">
           <value>/WEB-INF/pages/</value>
       </property>
        
       <property name="suffix">
           <value>.jsp</value>
       </property>       
        
   </bean>
    
</beans>
:
在Spring應用程式 ContextLoaderListener 將讀取其他 XML 組態檔案(如下的 abc.xml 和 root-context.xml 兩個檔案)。 可能不需要組態 ContextLoaderListener,如果你的應用程式並不需要讀取其他XML組態檔案。
<!-- web.xml -->
<!-- Spring ContextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
 
<!-- Load by Spring ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
       /WEB-INF/root-context.xml,
       /WEB-INF/abc.xml
 </param-value>
</context-param>
  • /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>
  • HelloWorldController.java
package com.yiibai.springmvc;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HelloWorldController {
 
    @RequestMapping("/hello")
    public String hello(Model model) {
         
        model.addAttribute("greeting", "Hello Spring MVC");
         
        return"helloworld";
         
    }
 
}

  • helloworld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Spring4 MVC -HelloWorld</title>
</head>
<body>
    <h1>${greeting}</h1>
</body>
</html>

5- 執行Spring應用程式

首先,執行應用程式之前,需要構建整個專案。
右鍵單擊該專案並選擇:
  • Run As/Maven install



執行組態:



輸入:
  • Name: Run HelloSpringMVC
  • Base directory: ${workspace_loc:/HelloSpringMVC} =>${workspace_loc:/HelloSpringMVC Maven Webapp}
  • Goals: tomcat7:run

點選Run:

第一次執行該程式將需要幾分鐘(看你的網速),它需要下載 Tomcat 外掛庫才能執行。
一切準備就緒:

執行URL,如下圖:

6 - 應用程式的流程

完成您的專案後,並成功地在上一步中執行。現在,我們來看一看程式的執行方式。

7- 控制器和方法

7.1- HttpServletRequest & HttpServletResponse

可以使用 HttpServletRequest, HttpServletResponse 在控制器的方法中。
  • OtherExampleController.java
package com.yiibai.springmvc;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
public class OtherExampleController {
 
   ......
 
   @RequestMapping("/somePath")
   public String requestResponseExample(HttpServletRequest request,
           HttpServletResponse reponses, Model model) {
 
       // Todo something here
 
       return "someView";
   }
 
   ......
}

7.2- 控制器中的重定向

使用字首 "redirect:" ,該方法返回字串,可以重定向到另一頁面。參見圖:
  • RedirectExampleController.java
package com.yiibai.springmvc;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
public class RedirectExampleController {
 
    @RequestMapping(value = "/redirect", method = RequestMethod.GET)
    public String authorInfo(Model model) {
 
       // Do somethong here
 
        return "redirect:/hello";
    }
}
執行URL:

7.3- @RequestParam範例

使用@RequestParam 註解將請求引數系結到你的控制器方法引數。
下面的程式碼片段顯示了這個用法:
  • RequestParamExampleController.java
package com.yiibai.springmvc;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@Controller
public class RequestParamExampleController {
     
    @RequestMapping("/user")
    public String userInfo(Model model,
            @RequestParam(value = "name", defaultValue = "Guest") String name) {
 
        model.addAttribute("name", name);
 
        if("admin".equals(name)) {
            model.addAttribute("email", "[email protected]");
        } else{
            model.addAttribute("email", "Not set");
        }
        return "userInfo";
    }
  
}
  • /WEB-INF/pages/userInfo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>User Info</title>
</head>
<body>
 
   <h2>${name}</h2>
 
   Email: ${email}
   <br>
</body>
</html>
執行 URL:

7.4- @PathVariable範例

在Spring MVC中,可以使用@PathVariable註釋將一個方法引數系結到一個URI模板變數的值:
例如,這是一個模板的URI:
  • /web/fe/{sitePrefix}/{language}/document/{id}/{naturalText}
而下面的 URI 模板匹配上面:
  1. /web/fe/default/en/document/8108/spring-mvc-for-beginners
  2. /web/fe/default/vi/document/8108/spring-mvc-cho-nguoi-moi-bat-dau
  3. .....

下面的程式碼片段顯示了用法:
  • PathVariableExampleController.java
package com.yiibai.springmvc;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class PathVariableExampleController {
  
 
    /**
     * @PathVariable Example:
     *
     */
    @RequestMapping("/web/fe/{sitePrefix}/{language}/document/{id}/{naturalText}")
    public String documentView(Model model,
            @PathVariable(value = "sitePrefix") String sitePrefix,
            @PathVariable(value = "language") String language,
            @PathVariable(value = "id") Long id,
            @PathVariable(value = "naturalText") String naturalText) {
 
        model.addAttribute("sitePrefix", sitePrefix);
        model.addAttribute("language", language);
        model.addAttribute("id", id);
        model.addAttribute("naturalText", naturalText);
 
        String documentName = "Java tutorial for Beginners";
        if(id == 8108) {
            documentName = "Spring MVC for Beginners";
        }
 
        model.addAttribute("documentName", documentName);
 
        return "documentView";
    }
}
  • /WEB-INF/pages/documentView.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>${documentName}</title>
</head>
<body>
 
    <h3>${documentName}</h3>
 
    Site Prefix: ${sitePrefix}
    <br> Language: ${language}
    <br> ID: ${id}
    <br> Natural Text: ${naturalText}
    <br>
 
</body>
</html>
執行 URL:

7.5- @ResponseBody範例

如果您使用 @ResponseBody 注釋到方法, spring 將嘗試轉換它的返回值,並自動寫入到HTTP響應。在這種情況下,並不需要一個特定的檢視。
註:方法不一定需要返回字串型別。


使用@ResponseBody和方法返回字串的簡單例子。

  • ResponseBodyExample1Controller.java
package com.yiibai.springmvc;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class ResponseBodyExample1Controller {
 
    // Simple example, method returns String.
    @RequestMapping(value = "/saveResult")
    @ResponseBody
    publicString authorInfo(Model model) {
        return "saved";
    }
 
     
}
執行範例的結果:
使用@ResponseBody 的一個例子,方法返回一個物件。
程式碼下載:http://pan.baidu.com/s/1mgYKoA0