1. login.jsp
 
<s:form action="login" method="post">
<s:textfield name="username" label="username"></s:textfield>
<s:textfield name="password" label="password"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
2. struts.xml        <action name="login" class="test.LoginAction">
            <result name="success">/result.jsp</result>
            <result name="input">/login.jsp</result>
        </action>
3. LoginAction.java
  
    public class LoginAction extends ActionSupport { private String password;
private String username; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public String execute() throws Exception {
System.out.println("execute~~~~~~~~"); 
return "success";
} @Override
public void validate() {
System.out.println("validate~~~~~~~~~~~~"); 
if ( null == this.username.trim()) 
{
this.addFieldError("username", "username requires");
}
if ( null == this.password.trim()) 
{
this.addFieldError("password", "password required");
}
}4. 问题描述:   如果当username和password两个都没有填的时候,提交会转到成功的页面,而不是input页面,并且在控制台会打印出validate~~~~~~~~~~~~
execute~~~~~~~~
 
   我的struts版本是2.0.12的。

解决方案 »

  1.   

    我已经解决。
    原因是因为空字符串执行trim方法后会返回一个空的字符串对象,所以 null == this.username.trim() 返回true参考资料:
    trim()
    if there is no character ,then a new String object representing an empty string is created and returned
      

  2.   

    this.username == null || "".equals(this.username.trim())
    我的判断一直这么写
      

  3.   

    学习了,个人习惯
    null == this.username || "".equals(this.username.trim())