close

上一篇介紹完如何用Maven加入所需的library後,這篇開始正式介紹如何寫Spring MVC程式

首先,如之前所提到的,Spring MVC會將所有的Request先導向給一支叫做DispatcherServlet的程式
接著DispatcherServlet會決定要把這個Request交給哪個Controller做處理

設定Web.xml

為了達到這個目的,我們必須先在/WEB-INF/web.xml底下做好相關定義
(預設用Maven建的Web專案會沒有WEB-INF資料夾及web.xml檔,請自己手動建立一個)
web.xml的內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<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/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
         version="3.0">
  <display-name>SpringDemo</display-name>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

這邊有幾個地方需要稍作說明:
1. 首先,我們必須先宣告Spring所提供的DispatcherServlet
2. 另外,我們可以透過contextConfigLocation這個參數來設定我們會將Spring要用到的核心設定檔放在哪邊
 (若沒有對這個參數作設定,Spring預設會找尋 /WEB-INF/[DispatcherServlet-Name]-servlet.xml這個位置的檔案,
 以這邊的例子來說,即/WEB-INF/dispatcher-servlet.xml)
3. 接下來我們設定了servlet-mapping的url-pattern為 "/",表示我們將domain底下的所有Request都交由dispatcher這支servlet處理

建立Spring核心設定檔

在了解DispatcherServlet如何宣告後,接著我們需要建立剛剛提到的Spring核心設定檔
1. 先在WEB-INF資料夾底下,新增一個mvc-config.xml檔
2. 填寫mvc-config.xml內容,如下:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	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
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:component-scan base-package="allen0818.tutorial.*" />
    <mvc:annotation-driven />
    <mvc:resources mapping="/*.html" location="/" />
    <mvc:resources mapping="/js/**" location="/js/" />
    
    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

1.

    <context:component-scan base-package="allen0818.tutorial.*" />
    <mvc:annotation-driven />

 表示我們指定Spring只掃描位於allen0818.tutorial這個package底下的所有使用Annotation標記的程式 
 (Spring 2.5以後支援用Annotation來宣告Controller, Service ...等服務)

2.

    <mvc:resources mapping="/*.html" location="/" />
    <mvc:resources mapping="/js/**" location="/js/" />

 為了避免一些靜態資源(像是js, css, image ...等)的呼叫也被當作是Request而被DispatcherServlet處理,
 我們透過mvc:resources來告知Spring哪些路徑下的檔案要被視為例外來處理

3. 宣告viewResolver
 這邊宣告了Spring提供的viewResolver,表示說當controller要將結果回傳給前端的view時,只需要打上view的名稱
 程式會自動將其導向至/WEB-INF/jsp/底下的.jsp檔,而不用自己打上完整的路徑名稱

 

第一支Spring MVC程式

我們可以撰寫一支簡單的Spring MVC程式來確認Request是否會如我們預期的被處理
1. 在Source Packages資料夾中建立新的Class, 並命名為MainController.java

2. MainController.java內容如下:

package allen0818.tutorial.controller;

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

/**
 *
 * @author allen0818
 */
@Controller
public class MainController {
  @RequestMapping(value = "/helloSpring")
  public void sayHello() {
    System.out.println("MainController executes sayHello function ...");
  }
}

可以看到我們利用Annotation的方式將MainController標註為Controller,
接下來我們在sayHello這個函式上標註 @RequestMapping(value = "/helloSpring")
意思是說當使用者對網站下/helloSpring的Request時,Controller會將這個Request導向給sayHello這個函式做處理

這邊可以看到在sayHello函式中只簡單在主控台印了一段話,並沒有做任何導向給某一個view的動作
在Spring MVC的架構下,當Controller沒有指定要將結果導向給哪一個view時,預設會導向至名稱為Request名稱的view
以這邊為例,就是/WEB-INF/jsp/helloSpring.jsp

3. 因此我們需要再建立一個helloSpring.jsp來提供畫面的呈現,內容如下:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Hello Spring MVC</title>
    </head>
    <body>
        <h1>Hello, Spring MVC World!</h1>
    </body>
</html>

 

這樣一來,當我們對著瀏覽器輸入 http://localhost:8084/FirstSpringMvcProj/helloSpring 時,可以看到
這個Request已經順利被Controller處理完並導向至helloSpring.jsp頁面了,如下圖所示:

而目前的專案結構會呈現下面這個樣子:

 

參考資料:

1. http://spring.io/blog/2011/01/04/green-beans-getting-started-with-spring-mvc/
2. http://hatemegalaxy.blogspot.tw/2013/07/spring-mvc-2-hello-spring-mvc.html
3. http://openhome.cc/Gossip/SpringGossip/FirstSpringMVC.html

 

arrow
arrow
    文章標籤
    NetBeans Maven Spring MVC
    全站熱搜

    allen0818 發表在 痞客邦 留言(0) 人氣()