Tuesday, August 6, 2013

Struts 2 Validation Using XML File Tutorial

In this example we will see how we can perform 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.
01.<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
03. 
04.<validators>
05.<field name="userName">
06.<field-validator type="requiredstring">
07.<message>User Name is required.</message>
08.</field-validator>
09.</field>
10.<field name="password">
11.<field-validator type="requiredstring">
12.<message key="password.required" />
13.</field-validator>
14.</field>
15.</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 errror 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.
01.public class Login extends ActionSupport {
02. 
03.private String userName;
04.private String password;
05. 
06.public Login() {
07.}
08. 
09.public String execute() {
10.return SUCCESS;
11.}
12. 
13.public String getUserName() {
14.return userName;
15.}
16. 
17.public void setUserName(String userName) {
18.this.userName = userName;
19.}
20. 
21.public String getPassword() {
22.return password;
23.}
24. 
25.public void setPassword(String password) {
26.this.password = password;
27.}
28.}
The login.jsp page contains the following code.
01.<%@page contentType="text/html" pageEncoding="UTF-8"%>
02.<%@taglib uri="/struts-tags" prefix="s" %>
03.<html>
04.<head>
05.<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
06.<title>Login Page</title>
07.<s:head />
08.</head>
09.<body>
10.<s:form action="LoginAction">
11.<s:textfield name="userName" label="User Name" />
12.<s:password name="password" label="Password" />
13.<s:submit value="Login" />
14.</s:form>
15.</body>
16.</html>
The <s:head /> tag is used to include the required css and js file for the selected theme. By default thexhtml theme is used.
Execute the example and click the Login button without entering the user name and password the following page will be displayed.
Enter a user name and password and click the Login button the following success page will be displayed.

No comments:

Post a Comment