快速使用struts1

Struts1

* apache公司提供的開源子項目、是基於MVC設計模式的web層(VC)實現、是出現最早的web層框架、應用廣泛。關注重點是Controller。
* 1、爲什麼使用框架?
    幫助我們快速構建項目、提升程序系統功能。讓我們編程時更多的關注業務邏輯、而不是系統問題。
* 2、Struts1組成
    * 1、ActionServlet 核心控制器
    * 2、FormBean 映射我們前端的form表單
    * 3、Action                 動作-用例
    * 4、ActionForward 轉向

    * 5、struts-config.xml 配置struts相關內容

配置Struts1

1).添加jar包


2).配置web-xml添加

<!-- struts1的配置信息 -->
    <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>
<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>action</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

<!-- end -->



3).配置struts-config.xml

<!-- 控制層和業務層的接口:Action -->
<action-mappings>
    <!-- path是Action的訪問路勁、name是關聯的FormBean -->
    <!-- scope="request":作用域、默認不寫是session -->
  <action path="/login" name="loginFormBean" type="cn.com.action.LoginAction" scope="request">
    <!-- 轉向的路勁 -->
<forward name="success" path="/main.jsp" redirect="true"></forward>
<forward name="error" path="/error.jsp"></forward>
  </action>

</action-mappings>



4).創建FormBean繼承自ActionForm、其所包含的屬性就是前端表單傳輸的表單輸入域的名字。

    <input type="text" name="username"/>


5).創建LoginAction類繼承自Action、重寫execute方法。參數form就是配置文件中的FormBean。

    * 頁面跳轉方案:
        * 方案1:轉發、服務器轉發、所以地址欄不變、樂意攜帶請求範圍內對象繼續傳遞。
    request.getRequestDispatcher.forword("/main.jsp");* 注意/到項目根目錄下
        
* 方案2:重定向、客戶端行爲、地址欄改變、可以攜帶session範圍對象傳遞
    reponse.sendRedirector("/jsp01/main.jsp");注意/會到達主機根目錄


6).通過filter過濾中文post請求

通過ActionForm中使用實體類來避免FormBean和實體Bean反覆轉化的問題。

addBook(Book book);
ActionForm{

    int bid;

    String  bname;

    String price;

    String author;

    Bookbean bb;

}

BookBean{

    int bid;

    String  bname;

    String price;

    String author;

}

Action{
    ActionForm actionForm = (ActionForm)form;
    addBook(actionForm.getBookBean());

}


實現一個Action處理多個請求。
* 1、繼承自dispatchAction、不要重寫默認的execute方法。
* 2、編寫自定義方法、參數和返回值與默認方法相同。

public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws Exception {
}
* 3、編寫struts-config.xml中的Action配置添加參數params。


<!-- /meth.do?method=add   會調用add方法 -->
<action path="/math" parameter="method" name="mathForm" type="cn.com.action.MathAction">
<forward name="success" path="/result.jsp"></forward>
</action>

* 4、前端網頁加傳參數method={?}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章