jpetstore 中的struts解析

 

Struts總結

2011.11.6

Jpetstore的實現主要用了兩個重要的東西,一個是struts,另一個是ibatis

首先總結一個struts。據我瞭解,struts其實就是在MVC模式的基礎上進行了完善的函數封裝。使得我們更加高效的進行Web應用開發。因此,struts就是面向對象的設計,也就是一個個功能齊全的類。所以,使用很方便。

struts能夠很好的分離出業務邏輯層,使得jsp與事務處理之間交叉更少,使得邏輯流程更加清晰明瞭。同時struts很好的實現了請求的過濾和請求的跳轉。

MVC設計模式

M: Model(Business process layer),模型,操作數據的業務處理層,並獨立於表現層V,主要設計數據庫的各種操作

V: View(Presentation layer),視圖,就是用戶交互界面,在VC之間進行數據的交互

C: Controller(Control layer),控制器,也就是視圖層和模型層橋樑,控制數據的流向,接受視圖層發出的事件,並重繪視圖。

Struts 提供的API

M:由於不同的web開發,會有不同業務邏輯,因此就沒有提供相應的類。因此ibatis的引進完善這個體系,使得數據的存儲變得更加靈活。

VStruts提供了action form創建form bean, 用於在controllerview間傳輸數據。

C:Struts提供了一個核心的控制器ActionServlet,通過這個核心的控制器來調用其他用戶註冊了的自定義的控制器Action,自定義Action需要符合Struts的自定義Action規範,還需要在struts-config.xml的特定配置文件中進行配置,接收JSP輸入字段形成Action form,然後調用一個Action控制器。Action控制器中提供了model的邏輯接口。

對比jpetstore上的代碼(如登陸驗證操作):

signonForm.jsp

  <html:form action="/shop/signon" method="POST">

    <p>Please enter your username and password.</p>

    <p>

      Username:<input type="text" name="username" value="j2ee"/>

      <br/>

      Password:<input type="password" name="password" value="j2ee"/>

    </p>

    <input type="submit" name="submit" value="Login"/>

  </html:form>

Struts-config.xml

 <form-bean name="accountBean"

 type="com.ibatis.jpetstore.presentation.AccountBean"/>

...

<action path="/shop/signon"

type="org.apache.struts.beanaction.BeanAction"

            name="accountBean" scope="session"

            validate="false">

      <forward name="success" path="/shop/index.shtml"/>

</action>

Web.xml

<servlet>

    <servlet-name>action</servlet-name>

    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

    <init-param>

      <param-name>config</param-name>

      <param-value>/WEB-INF/struts-config.xml</param-value>

    </init-param>

    <init-param>

      <param-name>debug</param-name>

      <param-value>2</param-value>

    </init-param>

    <init-param>

      <param-name>detail</param-name>

      <param-value>2</param-value>

    </init-param>

    <load-on-startup>2</load-on-startup>

  </servlet>

AccountBean.java

 public String signon() {

    account = accountService.getAccount(account.getUsername(), account.getPassword());

    if (account == null || account == null) {

      String value = "Invalid username or password.  Signon failed.";

      setMessage(value);

      clear();

      return FAILURE;

    } else {

      account.setPassword(null);

      myList = catalogService.getProductListByCategory (account.getFavouriteCategoryId());

      authenticated = true;

      return SUCCESS;

    }

  }

總的來說,struts就是一個輔助的開發工具包,能夠以MVC框架來輔助開發者實現便捷的開發過程,使得我們只關注業務邏輯,而不需要去關注C層的實現過程。因爲struts已經把控制層完善得很好了。我們只需要把重點放到業務邏輯上,也就是M,數據層次邏輯。

發佈了13 篇原創文章 · 獲贊 6 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章