struts2簡單樣本,struts2樣本

來源:互聯網
上載者:User

struts2簡單樣本,struts2樣本

今天寫一個struts2的例子,目的是為了讓大家明白struts2的基本流程,其實架構沒有大家想象的那麼難,說白了struts2的本質就是一個大的Servlet,即原本需要提交到Servlet處理的部分現在通過設定檔將其交給普通的Class類進行處理。

首先建立一個javaWeb項目,然後把struts2所依賴的包匯入到lib下(可以百度一下也可以直接到官網上下載),然後在web.xml中對struts2進行配置,添加的內容如下:

1 <filter>2     <filter-name>struts2</filter-name>3     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>4 </filter>5 <filter-mapping>6     <filter-name>struts2</filter-name>7     <url-pattern>/*</url-pattern>8 </filter-mapping>

在index.jsp中寫如下代碼:

1 <form method="post" action="testAction">2         名稱:<input type="text" name="name"/>3         <input type="submit" value="提交"/>4     </form>

接下來是寫struts的設定檔struts.xml,內容如下:

 1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" 3  "http://struts.apache.org/dtds/struts-2.1.dtd"> 4 <struts> 5     <package name="testaction" namespace="/" extends="struts-default"> 6         <action name="testAction" class="com.struts.action.TestAction"> 7             <result name="success">/success.jsp</result> 8             <result name="error">/index.jsp</result> 9         </action>10     </package>11 </struts>

其中一個action對應一個響應,在index.jsp中action="testAction"所以此處action的name="testAction"這是一一對應的關係。然後此處的class對應的則是交給誰去處理,根據設定檔我們在com.struts.action包中建立一個TestAction的類,此類的內容如下:

 1 package com.struts.action; 2  3 public class TestAction { 4     private String name; 5     public String getName() { 6         return name; 7     } 8     public void setName(String name) { 9         this.name = name;10     }11     public String execute(){12         if ("username".equals(name)) {13             return "success";14         } else {15             return "error";16         }17         18     }19 }

在這裡我們需要寫一個傳回值為String類型的execute方法,這裡的return對應struts.xml中的result的name屬性,而struts.xml中的result的內容這對應相應的頁面。

這裡的欄位名稱則是對應index.jsp中的name,一般我們在servlet中是用request.getParameter("name")得到的,但是在struts2中我們只需要把欄位封裝一下,剩下的交給struts2去做。

當然還有一個問題就是execute方法是預設的方法,如果我們的方法名稱不為execute則需要在struts.xml中的action中加一個屬性:method="對應方法名稱",這樣struts2就會調用對應類的對應方法。

在TestAction中的第12行這裡我只是進行了簡單的判斷,大家可以根據自身情況串連資料庫來做一個登陸的例子鍛煉一下。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.