2013-07-22 78 views
4

我在Struts 2中探索註釋。我嘗試使用@RequiredFieldValidator的簡單驗證沒有發生,表單提交空字段。我無法弄清楚,有人可以幫助我。Struts 2驗證使用註釋

我的JSP頁面:

<%@ page contentType="text/html; charset=UTF-8"%> 
<%@ taglib prefix="s" uri="/struts-tags" %> 
<html> 
<head> 
</head> 
<body> 
<h2>Struts 2 - Login Application</h2> 
<s:actionerror /> 
<s:fielderror /> 
<s:form action="login" method="post" namespace="/" > 
    <s:textfield name="username" key="label.username" size="20" /> 
    <s:password name="password" key="label.password" size="20" /> 
    <s:submit /> 
</s:form> 
</body> 
</html> 

我的動作類:

@Namespace("/") 

@Results({ 
@Result(name="success", location="/Welcome.jsp"), 
@Result(name="error", location="/Login.jsp") 
}) 


public class LoginAction extends ActionSupport implements ValidationAware { 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 5271055255991498361L; 
    private String username; 
    private String password; 


    public String execute() { 

     if (this.username.equals("admin") 
       && this.password.equals("admin123")) { 
      return "success"; 
     } else { 
      return "error"; 
     } 
    } 

    @RequiredFieldValidator(message = "The name is required") 
    public String getUsername() { 

     return username; 
    } 


    public void setUsername(String username) { 

     this.username = username; 
    } 

    @RequiredFieldValidator(message = "The password is required") 
    public String getPassword() { 
     return password; 
    } 

    public void setPassword(String password) { 
     this.password = password; 
    } 
} 

回答

1

您應該將驗證註解二傳手這樣

@RequiredStringValidator(type= ValidatorType.FIELD, message = "The name is required.") 
public void setUsername(String username) { 
    this.username = username; 
} 

RequiredFieldValidator檢查null值,但如果字符串字段爲空,則不是null,請使用RequiredStringValidator。你也應該在動作上運行validation攔截器。

此外,我認爲你應該仔細閱讀 a type conversion框架使用。

+0

它的工作原理,但爲什麼@RequiredFieldValidator不工作? – wolverine

+0

@ user1448660它可以用來驗證其他非'String'類型的值。轉換後,它檢查'null'。請刷新頁面,因爲您可能看不到最後的更改。 –