1. 程式人生 > >Spring4 MVC HelloWord實例

Spring4 MVC HelloWord實例

定向 字符串類型 rop cst www library res provided get

本教程是基於以下工具寫的:
  • 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,如下圖:
  • http://localhost:8080/HelloSpringMVC/hello
    技術分享

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:
  • http://localhost:8080/HelloSpringMVC/redirect
    技術分享

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:
  • http://localhost:8080/HelloSpringMVC/user?name=admin
    技術分享

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:
  • http://localhost:8080/HelloSpringMVC/web/fe/default/en/document/8108/spring-mvc-for-beginners
    技術分享

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";
    }
 
     
}
運行示例的結果:
  • http://localhost:8080/HelloSpringMVC/saveResult
    技術分享
使用@ResponseBody 的一個例子,方法返回一個對象。

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

Spring4 MVC HelloWord實例