Struts2驗證

在上一節的基礎之上,給項目加上驗證:非空和用戶名、密碼如果不是咱指定的也報錯

首先,修改Action類,要繼承ActionSupport類,然後,實現以下方法

public String execute() throws Exception{
		
		if("hello".equals(this.getUsername()) && "world".equals(this.getPassword())){
			
			return "success";
			
		}else{
			
			this.addFieldError("username", "username or password is wrong!");
			
			return "failure";
			
		}
	}

	public void validate() {
		
		//判斷用戶名密碼是否爲空
		if(null == this.getUsername() || "".equals(this.getUsername().trim())){
                       //當驗證不成功時,錯誤信息的顯示情況,這個是有針對性的,就像下邊這個,只針對“username”
			
			this.addFieldError("username", "username required!");
			
		}
		if(null == this.getPassword() || "".equals(this.getPassword().trim())){
			
			this.addFieldError("password", "password required!");
			
		}
		
	}

再修改struts.xml文件

<action name="login" class="tbk.struts.action.LoginAction">

			<result name="input">/login.jsp</result>

			<result name="success">/result.jsp</result>
			
			<result name="failure">/login.jsp</result>

		</action>


 解釋一下,<result  name="input">指的是,當驗證不成功的時候,要跳轉的頁面。

這樣就OK啦!

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