此文主要來自www.blogjava.net/Max的實例,自己是初學,自己動手實踐真的很有趣,有不對的地方希望大家給有指正。
首先login.jsp頁面表單:
<s:textfield name="username" label="USERNAME" tooltip="Enter Your UserName"></s:textfield>
<s:password name= "password" label="PASSWORD" tooltip="Enter Your PassWord"></s:password>
<s:submit label="login"></s:submit>
</s:form>
<result name="success">/welcome.jsp</result>
<result name="input">/login.jsp</result>
</action>
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String getUsername() {
System.out.println("******getUsername()*****");
return username;
}
public void setUsername(String username) {
System.out.println("*****setUsername()*****");
this.username = username;
}
public String getPassword() {
System.out.println("******getPassword()*****");
return password;
}
public void setPassword(String password) {
System.out.println("******setPassword******");
this.password = password;
}
@Override
public String execute() throws Exception {
System.out.println("*****execute()*****");
return SUCCESS;
}
@Override
public void validate() {
System.out.println("******validate******");
if(null == username || username.length() < 5) {
this.addFieldError("username","USERNAME ERROR");
}
if(null == password || password.length() < 5) {
this.addFieldError("password","PASSWORD ERROR");
}
}
}
YOUR PASSWORD:<FONT size="5" color="red"><s:property value="password"/></FONT><br>
*****setUsername()***** //set賦值操作
以上有struts2框架自動執行
******validate****** //表單驗證
*****execute()***** //業務邏輯
以上有struts2框架自動執行
******getUsername()***** //get方法得到值返回到welcome.jsp頁面
******getPassword()***** //get方法得到值返回到welcome.jsp頁面
客戶端輸入login.jsp表單傳回服務器時action="login" 請求轉發到struts.xml 匹配 name="login" class="com.bulktree.struts2.LoginAction" 找到處理請求的LoginAction類,進行自動set方法賦值,賦值後自動的執行 String execute()方法,返回String類型,默認爲SUCCESS,(即struts.xml文件裏action 的name屬性默認爲success)根據返回的String的值,決定執行哪個頁面
<result name="success">/welcome.jsp</result> “/”表示絕對路徑