使用注释进行Struts 2验证

时间:2013-07-22 10:08:08

标签: java jsp validation struts2 annotations

我在Struts 2中探索注释。使用@RequiredFieldValidator尝试的简单验证没有发生,表单提交空字段。我无法理解,有人可以帮助我。

我的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 个答案:

答案 0 :(得分:1)

您应该将验证器注释放在setter上,如下所示

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

RequiredFieldValidator会检查null值,但如果字符串字段为空,则字符串字段不是null,请使用RequiredStringValidator。您还应该在操作上运行validation拦截器。

此外,我认为您应该仔细阅读 框架使用的type conversion