- Overview of Spring MVC
- Spring MVC Request Processing Lifecycle
- Key Spring MVC Artifacts (~ items)
- DispatcherServlet
- Handlers
- Handler Mappings
- Views
- Quick Start
Spring MVC Overview
- The Spring web MVC framework provides model-view-controller MVC architecture and ready components that can be used to develop flexible and loosely coupled web applications.
- Spring's web framework
- Optional component build on top of the Spring framework
- Builds on the Java Servlet API
- A parallel Portlet version is also provided
- Comparable to Struts <-- v. important !
- Spring - A request-driven action framework
- Easy for Struts users to adopt while providing a stronger architectural foundation
- Compared with Struts, there are many benefits:
- For Spring, self contain, no need to depend on other libraries --> frew external dependencies
- Smart extension points --> chun guesses we can add function easy to control.
- Strong Integration >
- Link up/integrate with self files, pdf, jsp.
- Use Spring itself for configuration???
Spring MVC Architectural Strengths
- Simple model
- Easy to get going
- Core architecture has few external dependencies
- Designed for extension
- Smart extension points put you in control
- Layered architecture facilitates reuse
- Strong integration
- Integrates popular view and controller technologies
- Uses Spring itself for configuration
- All artifacts are testable and benefit from dependency injection
Spring MVC Integration
- Supported View Technologies
- JSP / JSTL
- Apache Velocity
- Freemaker
- Adobe PDF
- Microsoft Excel
- Jasper Reports
- XML / XSLT
- Supported Controller Technologies
- Multi Action, Form Controllers, Spring Web Flow
Other Key Features
- Data Binding Framework
- Validation Framework
- Internationalizaton (i18n) Support
- Tag Library
High-Level Spring MVC Request Processing Lifecycle
DispatcherServlet delegates a Handler
Handler (= Controller) - a middleware to return result view.
Key Spring MVC Artifacts
- DispatcherServlet
- Handler Mappings
- Handler
- Views
Artifacts - Spring MVC related items
(1) Dispatcher Servlet - The Heart of Spring MVC
- A Dispatcher Servlet is a front controller that coordinates the processing of all HTTP requests and response into the web application
- Dispatches requests to handlers ( = Controller)
- Issues appropriate responses to client (= View)
- Analogous (~Similar to) to a Struts Action Servlet
- But more powerful and customizable
- Deployable as a standard Java Servlet
- Uses Spring for configuration (i.e. web.xml)
- Has its own Spring ApplicationContext managing web-layer beans you define
- Delegates to these beans to carry out request processing
- Has full access to the "root" application context <-- v. important !
- Enables web beans to obtain references to application beans through dependency injection
Full access to the “root”
application context --> the key point !!!
The key point is “Has Full access
to the “root” application context
The “root” application context
links up Dispatcher Servlet easily. [mentioned in last session of middle tier].
Dispatcher Servlet Usage Considerations
- DispatcherServlets are coarse-grained (粗魯的) <-- web.xml???
- Define one per logical web application
- Not one per use case
- Generic dispatcher infrastructure can be used for several responsibilities
- To dispatch requests for HTML content
- To dispatch requests to web services
DispatcherServlet is not defined
in details, one web application just have an only one Dispatcher Servlet.
(2) Handler Mapping
The Dispatcher's HandlerMapping determines the handler of each request
URL-based HandlerMapping
- HandlerMapping rules you define are typically URL-based
- /login.htm=loginHandler
- /editAccount.htm=editAccountHandler
- /reward/*/**=rewardHandler
(3) Request Handlers (= Controller)
- Incoming requests are dispatched to handlers
- There are potentially many handlers per DispatcherServlet
- The Dispatcher's HandlerMapping determines the handler of each request
- Handlers you define are typically called Controllers
- Controller Results
- After request handling, Controllers return a result object called a ModelAndView
- Selects the view to render the response
- Contains the data needed for rendering
- The Model is the contract between the Controller and the View
- The same Controller often returns different ModelAndView objects
- To render different types of responses
- Example Controllers
- An AccountController that creats, shows, updates, and deletes Accounts in the database.
- A LoginController that logs users in.
- A TopPerformingAccountsController that generates an Excel spreadsheeet showing the top 20 accounts.
(4) View
Quick Start
-
Steps to developing web application functionality with Spring MVC
- 1. Deploy a Dispatcher Servlet (one-time only)
- 2. Implement a Controller
- 3. Implement the View(s)
- 4. Register the Controller with the DispatcherServlet
- 5. Deploy and test
- Repeat steps 2 - 5 to develop new functionality
Summary of Request Lifecycle
在Web MVC架構中,使用者並不直接連接至所需的資源,而必須先連接至前端控制器 (Front controller - DispatcherServlet),由前端控制器判斷使用者的請求要分派(Dispatch)給哪一個控制物件(Controller)來處理請求,藉此執到控制使 用者可請求的資源之目的。
在Spring 的Web MVC 框架中,擔任前端控制器角色的是org.springframework.web.servlet.DispatcherServlet,
(1) DispatcherServlet 負責將客戶的請求分派給對應於請求的控制物件,所以使用Spring Web MVC 的第一步,就是在web.xml 中定義 DispatcherServlet:
- web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee → http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <session-config> <session-timeout> 30 </session-timeout> </session-config> <servlet> <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
在 web.xml 中定義了一個 DispatcherServlet 的實例 dispatcherServlet,從設定中可以看到,所有連接至 *.do 結尾的請求都會由它來處理,"contextConfigLocation" 初始參數用來設定 Bean 定義檔的位置與名稱,如果不設置 "contextConfigLocation" 初始參數,則 DispatcherServlet 預設會使用 Servlet 的名稱為前置,讀取 「Servlet 名稱- servlet.xml」作為其 Bean 定義檔,在上面的設定中則會讀取 mvc-config.xml 中的定義。
您也可以定義多個 Bean 定義檔的來源,像是:
...
<servlet>
<servlet-name>hello</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,
→ /WEB-INF/other-service.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
<servlet>
<servlet-name>hello</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,
→ /WEB-INF/other-service.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
DispatcherServlet 負責轉發請求至控制物件(Controller),在Spring Web MVC 框架中,控制物件是實作org.springframework.web.servlet.mvc.Controller 介面的類別之實例, (3) Controller 介面有一個必須實作的handleRequest() 方法,其定義如下所示:
package org.springframework.web.servlet.mvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
public interface Controller {
ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
public interface Controller {
ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception;
}
當Controller 收到DispatcherServlet 轉發而來的請求,會執行 handleRequest() 方法來處理請求,處理完畢後返回一 個org.springframework.web.servlet.ModelAndView 的實例,ModelAndView 包括了要呈現在View 層(例如JSP網頁)的相關 Model 資料,以及其它有關View層的相關訊息。
在您第一個Spring Web MVC 中,使用者的請求將由一個HelloController 類別之實例來處理,其實作如下所示:
- HelloController.java
package onlyfun.caterpillar; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.mvc.Controller; import org.springframework.web.servlet.ModelAndView; public class HelloController implements Controller { private String viewPage; public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { String user = req.getParameter("user"); return new ModelAndView(viewPage, "user", user); } public void setViewPage(String viewPage) { this.viewPage = viewPage; } }
在這個Controller中,取得了來自使用者的 user 請求參數,並設定在 ModelAndView 的實例中,在這個例子中,建構 ModelAndView 的第一個引數 (argument) 為要呈現的目標網頁(或資源)路徑,第二個引數是設定用來取得Model 物件的鍵 (Key),而第三個引數為要給 View 層呈現資料用的Model 物件。
在Web MVC 架構下,控制物件(Controller) 的作用為收集使用者的請求,進行與 Web 層相關的動作,您不應當在控制物件中執行商務邏輯,也不應當讓 Servlet 相關的API 侵入至商務層,這會讓商務層的物件與Servlet API 產生耦合,例如讓 HttpServletRequest 物件直接設定至商務層物件之中。
使用Spring Web MVC 的好處是,Spring 的Controller 在其 IoC 容器管理下,可以如同一般的 Bean 來加以管理,並利用其依賴注入來完成相關物件的注入, 以這邊的例子來說,具體而言,您可以在 XML 檔案中設定Controller 請求處理完畢之後,所要呈現資料的網頁路徑,來看一下Bean 定義檔的內容, 依 web.xml 中的設定,請在WEB-INF目錄下建立 mvc-config.xml 檔案:
- mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC
"-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="viewResolver"
class="org.springframework.web.servlet.
→ view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean name="/hello.do"
class="onlyfun.caterpillar.HelloController">
<property name="viewPage">
<value>hello</value>
</property>
</bean>
</beans>
實際上DispatcherServlet 必須根據一個HandlerMapping物件來決定請求由哪一個Controller來處理, DispatcherServlet 預設使用 org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,也就是根據 Bean在定義時的"name"屬性及使用者請求的URL來決定使用哪一個Controller實例,例如在這個例子中,請求/hello.do時, DispatcherServlet 根據"hello"(即不包括.do)名稱決定要使用"name"為"hello"的Bean實例,所以就是將請求交 由HelloController 的實例來處理。
當Controller 返回 ModelAndView 後,DispatcherServlet 會交由 ViewResolver 物件來作 View 層的相關解 析,因而您需要設置一個ViewResolver 實例,在這個範例中將以 JSP 作為 View 層技術,所以使用 org.springframework.web.servlet.view.InternalResourceViewResolver, InternalResourceViewResolver 需要設置一個"viewClass",預設是 org.springframework.web.servlet.view.InternalResourceView,這個類別支援Servlet技 術的相關資源(像是JSP、Servlet)。
InternalResourceViewResolver的"prefix"、"suffix"屬性會與ModelAndView返回的路徑資訊結合, 例如若路徑資訊返回為"hello"字串,則與以上的例子設定結合,實際的路徑就是/WEB-INF/jsp/hello.jsp。
最後可以簡單的在/WEB-INF/jsp/中寫一個測試的hello.jsp:
- hello.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>First Spring MVC</title>
</head>
<body>
<h1>Hello, ${user}!!</h1>
</body>
</html>
在ModelAndView 中設置的Model物件,經由InternalResourceViewResolver 及 InternalResourceView 的解析,將設定為 JSP 技術中可存取的屬性(Attribute),因而可以使用JSP 技術中的 Expression Language 來取得資料,依以上所撰寫的程式,如果您在請求 hello.do 時附帶了user參數,則最後的 JSP 會出現您所給的 user 訊息。
No comments:
Post a Comment