简体   繁体   中英

Struts 2 validation using annotation

I am exploring annotation in Struts 2. The simple validation that am trying using @RequiredFieldValidator is not happening, the form submits empty fields. I could not figure it out, can someone help me.

My JSP page:

<%@ 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>

My action class:

@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;
    }
}

You should place the validator annotations on setter like this

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

RequiredFieldValidator checks the null values but string field are not null if they are empty, use RequiredStringValidator . Also you should run the validation interceptor on the action.

Also, I think you should read carefully a type conversion used by the framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM