Struts 2 validation is configured via XML or annotations. Manual validation in the action is also possible, and may be combined with XML and annotation-driven validation, see more about Struts 2 Validation.
In this example we will see one simple user name manual validation in action class.
1. Create a web project.
Create a dynamic web project and all struts 2 related jars in to lib folder. Here is the final structure of this example.
2. Create an Action class (UserAction.java)
The validate method is taking care validating and throwing error messages.
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String execute() {
setName("Hello " + name + " Welcome to Struts 2");
return SUCCESS;
}
public void validate() {
if (getName().length() == 0) {
addFieldError("name", "Name should not be blank");
} else if (!getName().equals("pretech")) {
this.addActionError(getText("Invalid user"));
}
}
}
3. Create a JSP page (index.jsp)
This jsp file contains input field for user name and submit button
<html>
<head>
<s:head/>
</head>
<body>
<h4>Welcome to Struts 2</h4>
<s:actionerror/>
<s:form action="userAction">
<s:textfield name="name" label="Enter your nme" /><br>
<s:submit value="submit" align="center" />
</s:form>
</body>
</html>
4. Create a success page
<html>
<head></head>
<body>
<h4>
<s:property value="name" />
</h4>
</body>
</html>
5. Struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml"/>
<package name="a" extends="struts-default">
<action name="userAction" class="com.pretech.UserAction">
<result name="success">/success.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>
6. Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Struts2SimpleValidation</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
7. Test Validation
Run this application and click on submit button without any username , we will see below validation error messages
Download this example: Struts 2 Simple Validation
No comments:
Post a Comment