3

I want to validate forms in Struts 2 using validate functions in the action class.

I found this example : http://www.javatpoint.com/struts-2-custom-validation-workflow-interceptor

However, I want to have multiple functions (actions) in the same class. And I want to have a validation function for each of these functions. How can we do this?

Edit:

The validate() function in the example gets invoked automatically since it is one of the Validateable interface functions. If I have validate functions with other names they won't be invoked

4

2 回答 2

6

Create validateXxx methods where Xxx is the name of the related action method.

(Whether or not this is the best option depends on the particular validations you need.)

于 2013-08-14T04:04:59.017 回答
2

validations using XML validation file

The naming convention of the XML validation file should be ActionClass-Validation.xml. Here our Action Class name is "Login.java" and the XML validation file name is "Login-Validation.xml".

The Login-Validation.xml file contains the following code. view source print?

<validators>
<field name="userName">
<field-validator type="requiredstring">
<message>User Name is required.</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="password.required" />
</field-validator>
</field>
</validators>

The field element contains the name of the form property that needs to be validated. The filed-validator element inside the field element contains the type of validation that needs to be performed.

Here you can either specify the error message directly using the message element or you can use the properties file to define all the error messages and use the key attribute to specify the error key.

Note the properties file should also have the same name as the Action class.

The Login Action class contains the following code. view source print?

public class Login extends ActionSupport {

private String userName;
private String password;

public Login() {
}

public String execute() {
return SUCCESS;
}

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

The login.jsp page contains the following code.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<s:head />
</head>
<body>
<s:form action="LoginAction">
<s:textfield name="userName" label="User Name" />
<s:password name="password" label="Password" />
<s:submit value="Login" />
</s:form>
</body>
</html>
于 2013-08-14T04:22:20.747 回答