7.Spring Web MVC 框架

1.Spring Web MVC 框架

MVC 框架教程

Spring web ? ? ? ? MVC 框架提供了模型-視圖-控制的體系結(jié)構(gòu)和可以用來開發(fā)靈活、松散耦合的 web 應(yīng)用程序的組件。MVC 模式導(dǎo)致了應(yīng)用程序的不同方面(輸入邏輯、業(yè)務(wù)邏輯和 UI 邏輯)的分離,同時(shí)提供了在這些元素之間的松散耦合。

模型封裝了應(yīng)用程序數(shù)據(jù),并且通常它們由 POJO 組成。

視圖主要用于呈現(xiàn)模型數(shù)據(jù),并且通常它生成客戶端的瀏覽器可以解釋的 HTML 輸出。

控制器主要用于處理用戶請求,并且構(gòu)建合適的模型并將其傳遞到視圖呈現(xiàn)。

DispatcherServlet

Spring Web 模型-視圖-控制(MVC)框架是圍繞?DispatcherServlet?設(shè)計(jì)的,DispatcherServlet?用來處理所有的 HTTP 請求和響應(yīng)。Spring Web MVC?DispatcherServlet?的請求處理的工作流程如下圖所示:

下面是對應(yīng)于?DispatcherServlet?傳入 HTTP 請求的事件序列:

收到一個(gè) HTTP 請求后,DispatcherServlet?根據(jù)?HandlerMapping?來選擇并且調(diào)用適當(dāng)?shù)?i>控制器。

控制器接受請求,并基于使用的 GET 或 POST 方法來調(diào)用適當(dāng)?shù)?service 方法。Service 方法將設(shè)置基于定義的業(yè)務(wù)邏輯的模型數(shù)據(jù),并返回視圖名稱到?DispatcherServlet?中。

DispatcherServlet?會(huì)從?ViewResolver?獲取幫助,為請求檢取定義視圖。

一旦確定視圖,DispatcherServlet?將把模型數(shù)據(jù)傳遞給視圖,最后呈現(xiàn)在瀏覽器中。

上面所提到的所有組件,即 HandlerMapping、Controller 和 ViewResolver 是?WebApplicationContext?的一部分,而?WebApplicationContext?是帶有一些對 web 應(yīng)用程序必要的額外特性的?ApplicationContext?的擴(kuò)展。

需求的配置

你需要映射你想讓?DispatcherServlet?處理的請求,通過使用在?web.xml?文件中的一個(gè) URL 映射。下面是一個(gè)顯示聲明和映射?HelloWeb?DispatcherServlet?的示例:

web.xml?文件將被保留在你的應(yīng)用程序的?WebContent/WEB-INF?目錄下。好的,在初始化?HelloWeb?DispatcherServlet?時(shí),該框架將嘗試加載位于該應(yīng)用程序的?WebContent/WEB-INF?目錄中文件名為?[servlet-name]-servlet.xml?的應(yīng)用程序內(nèi)容。在這種情況下,我們的文件將是?HelloWeb-servlet.xml

接下來,?標(biāo)簽表明哪些 URLs 將被 DispatcherServlet 處理。這里所有以?.jsp?結(jié)束的 HTTP 請求將由?HelloWeb?DispatcherServle t處理。

如果你不想使用默認(rèn)文件名?[servlet-name]-servlet.xml?和默認(rèn)位置?WebContent/WEB-INF,你可以通過在 web.xml 文件中添加 servlet 監(jiān)聽器?ContextLoaderListener?自定義該文件的名稱和位置,如下所示:

<web-app...>....<context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/HelloWeb-servlet.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>

現(xiàn)在,檢查?HelloWeb-servlet.xml?文件的請求配置,該文件位于 web 應(yīng)用程序的?WebContent/WEB-INF?目錄下:

? http://www.springframework.org/schema/beans

? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

? http://www.springframework.org/schema/context

? http://www.springframework.org/schema/context/spring-context-3.0.xsd">

以下是關(guān)于?HelloWeb-servlet.xml?文件的一些要點(diǎn):

[servlet-name]-servlet.xml?文件將用于創(chuàng)建 bean 定義,重新定義在全局范圍內(nèi)具有相同名稱的任何已定義的 bean。

標(biāo)簽將用于激活 Spring MVC 注釋掃描功能,該功能允許使用注釋,如 @Controller 和 @RequestMapping 等等。

InternalResourceViewResolver?將使用定義的規(guī)則來解決視圖名稱。按照上述定義的規(guī)則,一個(gè)名稱為?hello?的邏輯視圖將發(fā)送給位于?/WEB-INF/jsp/hello.jsp?中實(shí)現(xiàn)的視圖。

下一節(jié)將向你展示如何創(chuàng)建實(shí)際的組件,例如控制器,模式和視圖。

定義控制器

DispatcherServlet 發(fā)送請求到控制器中執(zhí)行特定的功能。@Controller?注釋表明一個(gè)特定類是一個(gè)控制器的作用。@RequestMapping?注釋用于映射 URL 到整個(gè)類或一個(gè)特定的處理方法。

@Controller@RequestMapping("/hello")publicclassHelloController{@RequestMapping(method = RequestMethod.GET)publicStringprintHello(ModelMap model){? ? ? model.addAttribute("message","Hello Spring MVC Framework!");return"hello";? }}

@Controller?注釋定義該類作為一個(gè) Spring MVC 控制器。在這里,第一次使用的?@RequestMapping?表明在該控制器中處理的所有方法都是相對于?/hello?路徑的。下一個(gè)注釋?@RequestMapping(method = RequestMethod.GET)?用于聲明?printHello()?方法作為控制器的默認(rèn) service 方法來處理 HTTP GET 請求。你可以在相同的 URL 中定義其他方法來處理任何 POST 請求。

你可以用另一種形式來編寫上面的控制器,你可以在?@RequestMapping?中添加額外的屬性,如下所示:

@ControllerpublicclassHelloController{@RequestMapping(value ="/hello", method = RequestMethod.GET)publicStringprintHello(ModelMap model){? ? ? model.addAttribute("message","Hello Spring MVC Framework!");return"hello";? }}

屬性表明 URL 映射到哪個(gè)處理方法,方法屬性定義了 service 方法來處理 HTTP GET 請求。關(guān)于上面定義的控制器,這里有以下幾個(gè)要注意的要點(diǎn):

你將在一個(gè) service 方法中定義需要的業(yè)務(wù)邏輯。你可以根據(jù)每次需求在這個(gè)方法中調(diào)用其他方法。

基于定義的業(yè)務(wù)邏輯,你將在這個(gè)方法中創(chuàng)建一個(gè)模型。你可以設(shè)置不同的模型屬性,這些屬性將被視圖訪問并顯示最終的結(jié)果。這個(gè)示例創(chuàng)建了一個(gè)帶有屬性 “message” 的模型。

一個(gè)定義的 service 方法可以返回一個(gè)包含視圖名稱的字符串用于呈現(xiàn)該模型。這個(gè)示例返回 “hello” 作為邏輯視圖的名稱。

創(chuàng)建 JSP 視圖

對于不同的表示技術(shù),Spring MVC 支持許多類型的視圖。這些包括 JSP、HTML、PDF、Excel 工作表、XML、Velocity 模板、XSLT、JSON、Atom 和 RSS 提要、JasperReports 等等。但我們最常使用利用 JSTL 編寫的 JSP 模板。所以讓我們在 /WEB-INF/hello/hello.jsp 中編寫一個(gè)簡單的?hello?視圖:

Hello Spring MVC

${message}

其中,${message}?是我們在控制器內(nèi)部設(shè)置的屬性。你可以在你的視圖中有多個(gè)屬性顯示。




2.Spring MVC Hello World 例子

Spring MVC Hello World 例子

下面的例子說明了如何使用 Spring MVC 框架來編寫一個(gè)簡單的基于 web 的 Hello World 應(yīng)用程序。下面讓我們使用 Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個(gè)動(dòng)態(tài) Web 應(yīng)用程序:

步驟描述

1創(chuàng)建一個(gè)名稱為?HelloWeb?的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint

2將上面提到的 Spring 和其他庫拖拽到文件夾?WebContent/WEB-INF/lib?中。

3在?com.tutorialspoint?包下創(chuàng)建一個(gè) Java 類?HelloController。

4在?WebContent/WEB-INF?文件夾下創(chuàng)建 Spring 的配置文件?Web.xml?和?HelloWeb-servlet.xml。

5在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?jsp?的子文件夾。在這個(gè)子文件夾下創(chuàng)建一個(gè)視圖文件?hello.jsp。

6最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。

這里是?HelloController.java?文件的內(nèi)容:

packagecom.tutorialspoint;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.ui.ModelMap;@Controller@RequestMapping("/hello")public class HelloController{? ? @RequestMapping(method= RequestMethod.GET)? public String printHello(ModelMap model) {model.addAttribute("message", "HelloSpringMVCFramework!");return"hello";? }}

下面是 Spring Web 配置文件?web.xml?的內(nèi)容

? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">Spring MVC ApplicationHelloWeborg.springframework.web.servlet.DispatcherServlet1HelloWeb/

下面是另一個(gè) Spring Web 配置文件?HelloWeb-servlet.xml?的內(nèi)容

? http://www.springframework.org/schema/beans? ?

? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

? http://www.springframework.org/schema/context

? http://www.springframework.org/schema/context/spring-context-3.0.xsd">

下面是 Spring 視圖文件?hello.jsp?的內(nèi)容

<%@pagecontentType="text/html; charset=UTF-8"%>Hello World

${message}

最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫。你僅僅需要將這些文件拖拽到?WebContent/WEB-INF/lib?文件夾中。

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用?Export > WAR File?選項(xiàng),在 Tomcat 的?webapps?文件夾中保存你的?HelloWeb.war?文件。

現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面?,F(xiàn)在嘗試訪問該 URL?http://localhost:8080/HelloWeb/hello。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:

你應(yīng)該注意,在給定的 URL 中,HelloWeb?是這個(gè)應(yīng)用程序的名稱,并且?hello?是我們在控制器中使用 @RequestMapping("/hello") 提到的虛擬子文件夾。當(dāng)使用?@RequestMapping("/")?映射你的 URL 時(shí),你可以使用直接 root,在這種情況下,你可以使用短 URL?http://localhost:8080/HelloWeb/?訪問相同的頁面,但是建議在不同的文件夾下有不同的功能。




3.Spring MVC 表單處理例子

Spring MVC 表單處理例子

下面的例子說明了如何編寫一個(gè)簡單的基于 web 的應(yīng)用程序,它利用了使用 Spring 的 Web MVC 框架的 HTML 表單。為了開始使用它,讓我們在恰當(dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個(gè)動(dòng)態(tài)的基于表單的 Web 應(yīng)用程序:

步驟描述

1創(chuàng)建一個(gè)名稱為?HelloWeb?的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint。

2將上面提到的 Spring 和其他庫拖拽到文件夾?WebContent/WEB-INF/lib?中。

3在?com.tutorialspoint?包下創(chuàng)建一個(gè) Java 類?Student?和?StudentController

4在?WebContent/WEB-INF?文件夾下創(chuàng)建 Spring 的配置文件?Web.xml?和?HelloWeb-servlet.xml。

5在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?jsp?的子文件夾。在這個(gè)子文件夾下創(chuàng)建視圖文件?student.jsp?和?result.jsp。

6最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。

這里是?Student.java?文件的內(nèi)容:

packagecom.tutorialspoint;publicclassStudent{privateInteger age;privateString name;privateInteger id;publicvoidsetAge(Integer age){this.age = age;? }publicIntegergetAge(){returnage;? }publicvoidsetName(String name){this.name = name;? }publicStringgetName(){returnname;? }publicvoidsetId(Integer id){this.id = id;? }publicIntegergetId(){returnid;? }}

下面是?StudentController.java?文件的內(nèi)容:

packagecom.tutorialspoint;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.ModelAttribute;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.servlet.ModelAndView;importorg.springframework.ui.ModelMap;@ControllerpublicclassStudentController{@RequestMapping(value ="/student", method = RequestMethod.GET)publicModelAndViewstudent(){returnnewModelAndView("student","command",newStudent());? }@RequestMapping(value ="/addStudent", method = RequestMethod.POST)publicStringaddStudent(@ModelAttribute("SpringWeb")Student student,? ? ModelMap model){? ? ? model.addAttribute("name", student.getName());? ? ? model.addAttribute("age", student.getAge());? ? ? model.addAttribute("id", student.getId());return"result";? }}

在這里,第一個(gè) service 方法?student(),我們已經(jīng)在名稱為 “command” 的 ModelAndView 對象中傳遞一個(gè)空的?Student?對象,因?yàn)?spring 框架需要一個(gè)名稱的 “command” 的對象,如果你在 JSP 文件中使用 標(biāo)簽。所以,當(dāng)?student()?方法被調(diào)用時(shí),它返回?student.jsp?視圖。

第二個(gè) service 方法?addStudent()?將調(diào)用?HelloWeb/addStudent?URL 中的 POST 方法。你將根據(jù)提交的信息準(zhǔn)備好你的模型對象。最后一個(gè) “result” 視圖會(huì)從 service 方法中返回,它將導(dǎo)致呈現(xiàn) result.jsp。

下面是 Spring Web 配置文件?web.xml?的內(nèi)容

? ? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">Spring MVC Form HandlingHelloWeborg.springframework.web.servlet.DispatcherServlet1HelloWeb/

下面是另一個(gè) Spring Web 配置文件?HelloWeb-servlet.xml?的內(nèi)容

? http://www.springframework.org/schema/beans? ?

? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

? http://www.springframework.org/schema/context

? http://www.springframework.org/schema/context/spring-context-3.0.xsd">

下面是 Spring 視圖文件?student.jsp?的內(nèi)容

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring MVC Form Handling

Student Information

NameAgeid

下面是 Spring 視圖文件?result.jsp?的內(nèi)容

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring MVC Form Handling

Submitted Student Information

Name${name}Age${age}ID${id}

最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫的列表。你僅僅需要將這些文件拖拽到?WebContent/WEB-INF/lib?文件夾中。

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用?Export > WAR File?選項(xiàng),并且在 Tomcat 的?webapps?文件夾中保存你的?HelloWeb.war?文件。

現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面。現(xiàn)在嘗試訪問該 URL?http://localhost:8080/HelloWeb/student。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:

在提交必需的信息之后,單擊提交按鈕來提交這個(gè)表單。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:





4.Spring 頁面重定向例子

Spring 頁面重定向例子

下面的例子說明了如何編寫一個(gè)簡單的基于 web 的應(yīng)用程序,它利用重定向來傳送一個(gè) http 請求到另一個(gè)頁面中。為了開始使用它,讓我們在恰當(dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個(gè)動(dòng)態(tài)的基于表單的 Web 應(yīng)用程序:

步驟描述

1創(chuàng)建一個(gè)名稱為?HelloWeb?的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint。

2將上面提到的 Spring 和其他庫拖拽到文件夾?WebContent/WEB-INF/lib?中。

3在?com.tutorialspoint?包下創(chuàng)建一個(gè) Java 類?WebController

4在?WebContent/WEB-INF?文件夾下創(chuàng)建 Spring 的配置文件?Web.xml?和?HelloWeb-servlet.xml。

5在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?jsp?的子文件夾。在這個(gè)子文件夾下創(chuàng)建視圖文件?index.jsp?和?final.jsp。

6最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。

這里是?WebController.java?文件的內(nèi)容:

packagecom.tutorialspoint;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;@ControllerpublicclassWebController{@RequestMapping(value ="/index", method = RequestMethod.GET)publicStringindex(){return"index";? }@RequestMapping(value ="/redirect", method = RequestMethod.GET)publicStringredirect(){return"redirect:finalPage";? }@RequestMapping(value ="/finalPage", method = RequestMethod.GET)publicStringfinalPage(){return"final";? }}

下面是 Spring Web 配置文件?web.xml?的內(nèi)容

? ? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">Spring Page RedirectionHelloWeborg.springframework.web.servlet.DispatcherServlet1HelloWeb/

下面是另一個(gè) Spring Web 配置文件?HelloWeb-servlet.xml?的內(nèi)容

<?xml version="1.0"encoding="UTF-8"?>

? http://www.springframework.org/schema/beans? ?

? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

? http://www.springframework.org/schema/context

? http://www.springframework.org/schema/context/spring-context-3.0.xsd">

下面是 Spring 視圖文件?index.jsp?文件的內(nèi)容。這將是一個(gè)登陸頁面,這個(gè)頁面將發(fā)送一個(gè)請求來訪問重定向?service 方法,該方法將把這個(gè)請求重定向到另一個(gè) service 方法中,最后將顯示?final.jsp?頁面。

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring Page Redirection

Spring Page Redirection

Click below button to redirect the result to new page

下面是 Spring 視圖文件?final.jsp?的內(nèi)容。這是最終的重定向頁面。

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring Page Redirection

Redirected Page

最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫的列表。你僅僅需要將這些文件拖拽到?WebContent/WEB-INF/lib?文件夾中。

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用?Export > WAR File?選項(xiàng),并且在 Tomcat 的?webapps?文件夾中保存你的?HelloWeb.war?文件。

現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面?,F(xiàn)在嘗試訪問該 URL?http://localhost:8080/HelloWeb/index。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:

現(xiàn)在單擊 “Redirect Page” 按鈕來提交表單,并且得到最終的重定向頁面。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:




5.Spring 靜態(tài)頁面例子

Spring 靜態(tài)頁面例子

下面的例子說明了如何使用 Spring MVC 框架來編寫一個(gè)簡單的基于 web 的應(yīng)用程序,它可以在 <mvc:resources> 標(biāo)簽的幫助下訪問靜態(tài)頁面和動(dòng)態(tài)頁面。為了開始使用它,讓我們在恰當(dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個(gè)動(dòng)態(tài)的基于表單的 Web 應(yīng)用程序:

步驟描述

1創(chuàng)建一個(gè)名稱為?HelloWeb?的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint。

2將上面提到的 Spring 和其他庫拖拽到文件夾?WebContent/WEB-INF/lib?中。

3在?com.tutorialspoint?包下創(chuàng)建一個(gè) Java 類?WebController

4在?WebContent/WEB-INF?文件夾下創(chuàng)建 Spring 的配置文件?Web.xml?和?HelloWeb-servlet.xml。

5在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?jsp?的子文件夾。在這個(gè)子文件夾下創(chuàng)建一個(gè)視圖文件?index.jsp。

6在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?pages?的子文件夾。在這個(gè)子文件夾下創(chuàng)建一個(gè)靜態(tài)文件?final.htm

7最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。

這里是?WebController.java?文件的內(nèi)容:

packagecom.tutorialspoint;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;@ControllerpublicclassWebController{@RequestMapping(value ="/index", method = RequestMethod.GET)publicStringindex(){return"index";? }@RequestMapping(value ="/staticPage", method = RequestMethod.GET)publicStringredirect(){return"redirect:/pages/final.htm";? }}

下面是 Spring Web 配置文件?web.xml?的內(nèi)容

? ? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">Spring Page RedirectionHelloWeborg.springframework.web.servlet.DispatcherServlet1HelloWeb/

下面是另一個(gè) Spring Web 配置文件?HelloWeb-servlet.xml?的內(nèi)容

<?xml version="1.0"encoding="UTF-8"?>

http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

在這里,<mvc:resources..../>?標(biāo)簽被用來映射靜態(tài)頁面。?mapping?屬性必須是一個(gè)指定一個(gè) http 請求的 URL 模式的 Ant 模式。?location?屬性必須指定一個(gè)或者多個(gè)具有包含圖片,樣式表,JavaScript 和其他靜態(tài)內(nèi)容的靜態(tài)頁面的資源目錄位置。多個(gè)資源位置可以使用逗號(hào)分隔這些值的列表來被指定。

下面是 Spring 視圖文件?WEB-INF/jsp/index.jsp?的內(nèi)容。這將是一個(gè)登陸頁面,這個(gè)頁面將發(fā)送一個(gè)請求來訪問?staticPage?的 service 方法,它將重定向這個(gè)請求到 WEB-INF/pages 文件夾中的一個(gè)可用的靜態(tài)頁面。

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring Landing Page

Spring Landing Pag

Click below button to get a simple HTML page

下面是 Spring 視圖文件?WEB-INF/pages/final.htm?的內(nèi)容。

Spring Static Page

A simple HTML page

最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫的列表。你僅僅需要將這些文件拖拽到?WebContent/WEB-INF/lib?文件夾中。

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用?Export > WAR File?選項(xiàng),并且在 Tomcat 的?webapps?文件夾中保存你的?HelloWeb.war?文件。

現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面?,F(xiàn)在嘗試訪問該 URL?http://localhost:8080/HelloWeb/index。 如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:

單擊 “Get HTML Page” 按鈕來訪問 staticPage 中的 service 方法中提到的一個(gè)靜態(tài)頁面。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:



6.Spring 異常處理例子

Spring 異常處理例子

下面的例子說明了如何使用 Spring MVC 框架來編寫一個(gè)簡單的基于 web 的應(yīng)用程序,它可以處理它的內(nèi)置控制器產(chǎn)生的一個(gè)或多個(gè)異常。為了開始使用它,讓我們在恰當(dāng)?shù)奈恢檬褂?Eclipse IDE,然后按照下面的步驟使用 Spring 的 Web 框架來開發(fā)一個(gè)動(dòng)態(tài)的基于表單的 Web 應(yīng)用程序:

步驟描述

1創(chuàng)建一個(gè)名稱為?HelloWeb?的動(dòng)態(tài) Web 項(xiàng)目,并且在已創(chuàng)建的項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint

2將上面提到的 Spring 和其他庫拖拽到文件夾?WebContent/WEB-INF/lib?中。

3在?com.tutorialspoint?包下創(chuàng)建一個(gè) Java 類?StudentStudentController?和?SpringException。

4在?WebContent/WEB-INF?文件夾下創(chuàng)建 Spring 的配置文件?Web.xml?和?HelloWeb-servlet.xml

5在?WebContent/WEB-INF?文件夾下創(chuàng)建名稱為?jsp?的子文件夾。在這個(gè)子文件夾下創(chuàng)建視圖文件?student.jsp,result.jsp,error.jsp?和?ExceptionPage.jsp

6最后一步是創(chuàng)建所有的源代碼和配置文件的內(nèi)容,并導(dǎo)出該應(yīng)用程序,正如下面解釋的一樣。

這里是?Student.java?文件的內(nèi)容:

packagecom.tutorialspoint;publicclassStudent{privateInteger age;privateString name;privateInteger id;publicvoidsetAge(Integer age){this.age = age;? }publicIntegergetAge(){returnage;? }publicvoidsetName(String name){this.name = name;? }publicStringgetName(){returnname;? }publicvoidsetId(Integer id){this.id = id;? }publicIntegergetId(){returnid;? }}

下面是?SpringException.java?文件的內(nèi)容:

packagecom.tutorialspoint;publicclassSpringExceptionextendsRuntimeException{privateString exceptionMsg;publicSpringException(String exceptionMsg){this.exceptionMsg = exceptionMsg;? }publicStringgetExceptionMsg(){returnthis.exceptionMsg;? }publicvoidsetExceptionMsg(String exceptionMsg){this.exceptionMsg = exceptionMsg;? }}

下面是?StudentController.java?文件的內(nèi)容。這里,你需要使用?@ExceptionHandler?注解一個(gè) service 方法,你可以指定要處理的一個(gè)或多個(gè)異常。如果你要指定一個(gè)以上的異常,那么你可以使用逗號(hào)分隔這些值。

packagecom.tutorialspoint;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.ModelAttribute;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.servlet.ModelAndView;importorg.springframework.ui.ModelMap;@ControllerpublicclassStudentController{@RequestMapping(value ="/student", method = RequestMethod.GET)publicModelAndViewstudent(){returnnewModelAndView("student","command",newStudent());? }@RequestMapping(value ="/addStudent", method = RequestMethod.POST)@ExceptionHandler({SpringException.class})publicStringaddStudent( @ModelAttribute("HelloWeb")Student student,? ? ? ModelMap model){if(student.getName().length() <5){thrownewSpringException("Given name is too short");? ? ? }else{? ? ? model.addAttribute("name", student.getName());? ? ? }if( student.getAge() <10){thrownewSpringException("Given age is too low");? ? ? }else{? ? ? model.addAttribute("age", student.getAge());? ? ? }? ? ? model.addAttribute("id", student.getId());return"result";? }}

下面是 Spring Web 配置文件?web.xml?的內(nèi)容

? ? http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">Spring Exception HandlingHelloWeborg.springframework.web.servlet.DispatcherServlet1HelloWeb/

下面是另一個(gè) Spring Web 配置文件?HelloWeb-servlet.xml?的內(nèi)容

http://www.springframework.org/schema/beans? ?

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

? ? ? SimpleMappingExceptionResolver">ExceptionPage

在這里,你指定?ExceptionPage?作為一個(gè)異常視圖,以便 SpringException 發(fā)生,如果有任何其他類型的異常發(fā)生,那么一個(gè)通用的視圖?error?會(huì)發(fā)生。

下面是 Spring 視圖文件?student.jsp?的內(nèi)容:

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring MVC Exception Handling

Student Information

NameAgeid

下面是 Spring 視圖文件?error.jsp?的內(nèi)容:

Spring Error Page

An error occured, please contact webmaster.

;

下面是 Spring 視圖文件?ExceptionPage.jsp?的內(nèi)容。在這里,你將通過 ${exception} 訪問異常實(shí)例。

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring MVC Exception Handling

Spring MVC Exception Handling

${exception.exceptionMsg}

下面是 Spring 視圖文件?result.jsp?的內(nèi)容:

<%@tagliburi="http://www.springframework.org/tags/form"prefix="form"%>Spring MVC Form Handling

Submitted Student Information

Name${name}Age${age}ID${id}

最后,下面是包含在你的 web 應(yīng)用程序中的 Spring 和其他庫的列表。你僅僅需要將這些文件拖拽到?WebContent/WEB-INF/lib?文件夾中。

commons-logging-x.y.z.jar

org.springframework.asm-x.y.z.jar

org.springframework.beans-x.y.z.jar

org.springframework.context-x.y.z.jar

org.springframework.core-x.y.z.jar

org.springframework.expression-x.y.z.jar

org.springframework.web.servlet-x.y.z.jar

org.springframework.web-x.y.z.jar

spring-web.jar

一旦你完成了創(chuàng)建源代碼和配置文件后,導(dǎo)出你的應(yīng)用程序。右鍵單擊你的應(yīng)用程序,并且使用?Export > WAR File?選項(xiàng),并且在 Tomcat 的?webapps?文件夾中保存你的?HelloWeb.war?文件。

現(xiàn)在啟動(dòng)你的 Tomcat 服務(wù)器,并且確保你能夠使用標(biāo)準(zhǔn)的瀏覽器訪問 webapps 文件夾中的其他 web 頁面。現(xiàn)在嘗試訪問該 URL?http://localhost:8080/SpringWeb/student。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:

輸入如上圖所示的值,然后單擊提交按鈕。如果你的 Spring Web 應(yīng)用程序一切都正常,你應(yīng)該看到下面的結(jié)果:




7.Spring 使用 Log4J 記錄日志

使用 Log4J 記錄日志

在 Spring 應(yīng)用程序中使用 Log4J 的功能是非常容易的。下面的例子將帶你通過簡單的步驟解釋 Log4J 和 Spring 之間的簡單集成。

假設(shè)你已經(jīng)在你的機(jī)器上安裝了?Log4J,如果你還沒有 Log4J,你可以從?http://logging.apache.org/?中下載,并且僅僅在任何文件夾中提取壓縮文件。在我們的項(xiàng)目中,我們將只使用?log4j-x.y.z.jar。

接下來,我們讓 Eclipse IDE 在恰當(dāng)?shù)奈恢霉ぷ?,遵循以下步驟,使用 Spring Web 框架開發(fā)一個(gè)基于 Web 應(yīng)用程序的動(dòng)態(tài)表單:

步驟描述

1創(chuàng)建一個(gè)名稱為?SpringExample?的項(xiàng)目,并且在創(chuàng)建項(xiàng)目的?src?文件夾中創(chuàng)建一個(gè)包?com.tutorialspoint。

2使用?Add External JARs?選項(xiàng),添加所需的 Spring 庫,解釋見?Spring Hello World Example?章節(jié)。

3使用?Add External JARs?選項(xiàng),同樣在你的項(xiàng)目中添加 log4j 庫?log4j-x.y.z.jar。

4在?com.tutorialspoint?包下創(chuàng)建 Java 類?HelloWorld?和?MainApp。

5在?src?文件中創(chuàng)建 Bean 配置文件?Beans.xml。

6在?src?文件中創(chuàng)建 log4J 配置文件?log4j.properties

7最后一步是創(chuàng)建的所有 Java 文件和 Bean 配置文件的內(nèi)容,并運(yùn)行應(yīng)用程序,解釋如下所示。

這個(gè)是?HelloWorld.java?文件的內(nèi)容:

packagecom.tutorialspoint;publicclassHelloWorld{privateString message;publicvoidsetMessage(String message){this.message? = message;? }publicvoidgetMessage(){? ? ? System.out.println("Your Message : "+ message);? }}

下面的是第二個(gè)文件?MainApp.java?的內(nèi)容:

packagecom.tutorialspoint;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.apache.log4j.Logger;publicclassMainApp{staticLogger log = Logger.getLogger(MainApp.class.getName());publicstaticvoidmain(String[] args){? ? ? ApplicationContext context =newClassPathXmlApplicationContext("Beans.xml");? ? ? log.info("Going to create HelloWord Obj");? ? ? HelloWorld obj = (HelloWorld) context.getBean("helloWorld");? ? ? obj.getMessage();? ? ? log.info("Exiting the program");? }}

使用與我們已經(jīng)生成信息消息類似的方法,你可以生成調(diào)試錯(cuò)誤消息?,F(xiàn)在讓我們看看?Beans.xml?文件的內(nèi)容:

? ? http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">? ? ? ? ?

下面是?log4j.properties?的內(nèi)容,它定義了使用 Log4J 生成日志信息所需的標(biāo)準(zhǔn)規(guī)則:

# Define the root logger with appender filelog4j.rootLogger = DEBUG, FILE# Define the file appenderlog4j.appender.FILE=org.apache.log4j.FileAppender# Set the name of the filelog4j.appender.FILE.File=C:\\log.out#Set the immediate flush totrue(default)log4j.appender.FILE.ImmediateFlush=true# Set the threshold to debug modelog4j.appender.FILE.Threshold=debug# Set the append tofalse, overwritelog4j.appender.FILE.Append=false# Define the layoutforfile appenderlog4j.appender.FILE.layout=org.apache.log4j.PatternLayoutlog4j.appender.FILE.layout.conversionPattern=%m%n

一旦你完成了創(chuàng)建源和 bean 的配置文件后,我們就可以運(yùn)行該應(yīng)用程序。如果你的應(yīng)用程序一切都正常,在 Eclipse 控制臺(tái)將輸出以下信息:

Your Message : Hello World!

同時(shí)如果你檢查你的 C:\ 驅(qū)動(dòng),那么你應(yīng)該發(fā)現(xiàn)含有各種日志消息的日志文件?log.out,其中一些如下所示:

Going to create HelloWord ObjReturning cached instance of singleton bean'helloWorld'Exiting the program

Jakarta Commons Logging (JCL) API

或者,你可以使用?Jakarta Commons Logging(JCL)?API 在你的 Spring 應(yīng)用程序中生成日志。JCL 可以從?http://jakarta.apache.org/commons/logging/?下載。我們在技術(shù)上需要這個(gè)包的唯一文件是?commons-logging-x.y.z.jar?文件,需要使用與上面的例子中你使用?log4j-x.y.z.jar?類似的方法來把?commons-logging-x.y.z.jar?放在你的類路徑中。

為了使用日志功能,你需要一個(gè)?org.apache.commons.logging.Log?對象,然后你可以根據(jù)你的需要調(diào)用任何一個(gè)下面的方法:

fatal(Object message)

error(Object message)

warn(Object message)

info(Object message)

debug(Object message)

trace(Object message)

下面是使用 JCL API 對 MainApp.java 的替換:

packagecom.tutorialspoint;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.apache.commons.logging. Log;importorg.apache.commons.logging. LogFactory;publicclassMainApp{staticLog log = LogFactory.getLog(MainApp.class.getName());publicstaticvoidmain(String[] args){? ? ? ApplicationContext context =newClassPathXmlApplicationContext("Beans.xml");? ? ? log.info("Going to create HelloWord Obj");? ? ? HelloWorld obj = (HelloWorld) context.getBean("helloWorld");? ? ? obj.getMessage();? ? ? log.info("Exiting the program");? }}

你應(yīng)該確保在編譯和運(yùn)行該程序之前在你的項(xiàng)目中已經(jīng)引入了?commons-logging-x.y.z.jar?文件。

現(xiàn)在保持在上面的例子中剩下的配置和內(nèi)容不變,如果你編譯并運(yùn)行你的應(yīng)用程序,你就會(huì)得到與使用 Log4J API 后獲得的結(jié)果類似的結(jié)果。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容