Struts - SPLessons

Struts 2 Validations

Home > Lesson > Chapter 30
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Struts 2 Validations

Struts 2 Validations

shape Description

Struts 2 Validations is an important task while using credentials, Validations are used to avoid the inconsistency result, by using the validation forms one can submit some values in a browser page. For example, give the input values in browser page, then the container will check, whether the given values is valid or not. If the entered value is wrong, the browser displays error message. Following are the different types of Struts 2 Validations.

By Custom Validations

shape Description

Custom Validations means to define an own logic in Validation page. When, one  write the validations in action class that class must be implemented a Validateable interface or extend ActionSupport class. Validateable interface or ActionSupport class provides the validate() method. Then, one can write the validation logics in Validate(). Action class will take the  result name as input by default, so configure the result name=" input " in struts.xml file.

shape Example

1. Create the project directory structure. 2. Create the View pages and forwarded the request to Action class.   index.jsp [java]<%@ taglib uri="/struts-tags" prefix="s" %> <s:form action="loginForm"> <s:textfield name="name" label="User Name"></s:textfield> <s:textfield name="email" label="Email Id"></s:textfield> <center> <s:submit value="Sign In"></s:submit> </center> </s:form> [/java] Here just created two text fields such as User Name and Email Id and also created submit button. success.jsp [java]<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <h1>Welcome to SPLessons</h1> You have successfully signed in Itoolsinfo.com. Employee Name : <s:property value="name" /> Employee Email : <s:property value="email" /> </body> </html><span style="line-height: 1.5;"> [/java] After enter the details if every thing is fine success message will be displayed. 3. Create the Action class by extending ActionSupport class. CustomValidations.java [java]package com.splessons; import com.opensymphony.xwork2.ActionSupport; public class CustomValidations extends ActionSupport { private String name; private String email; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void validate() { if(name.length()<1 || name.equals(" Joshaf ")) { addFieldError("name"," User name is Wrong ") ; } if(email.length()<1) { addFieldError("email", "Email can't be empty"); } } public String execute() { return "success"; } } [/java] Here just performed validation code that is name should be Joshaf and user must need to enter Email id. 4. Configure the Action class in struts.xml file. struts.xml [xml]<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" extends="struts-default"> <action name="loginForm" class="com.splessons.CustomValidations" > <result name="success">success.jsp</result> <result name="input">index.jsp</result> </action> </package> </struts> [/xml] Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined action class. web.xml [xml]<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> [/xml] The web.xml web application descriptor file represents the core of the Java web application, so it is appropriate that it is also part of the core of the Struts framework. In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests. This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave. 5. Run the application in the server, the browser display the output. 6.Enter all the required fields, then the browser display the output like. 7. If the values are not entered, then the browser display the output as some error message.

By Input Validations

shape Description

Struts 2 framework provides number of input validations or built-in validators and also known as bundled validators for input validations like email, phone number, user id. Bundled validators used two ways in Struts 2 xml file. 1. By using Plain-Validator syntax, 2. By using Field-Validator syntax. If we write validations in xml file, xml file name should be [Action class name]-validation.xml and it will stores the under classes folder. Plain-Validator syntax can be used for action level validator. In such case, a single validator can be applied to many fields. [xml] <validators> <!-- Plain-Validator Syntax --> <validator type="requiredstring"> <param name="fieldName"> Action class property </param> <param name="trim">true</true> <message>error message</message> </validator> </validators> [/xml] Field-Validator syntax can be used for field level validator, In such case multiple validators can be added to one field. [xml] <validators> <!-- Field-Validator Syntax --> <field name="property name"> <field-validator type="requiredString"> <param name="trim">true</param> <message> error message</message> </field-validator> </field> </validators></pre> <pre>[/xml]

shape Example

1. Create the project directory structure 2. Create the view pages. index.jsp [java] <pre><%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="/struts-tags" prefix="s" %> <html> <head> <STYLE type="text/css"> .errorMessage{color:red;} </STYLE> </head> <body> <s:form action="register"> <s:textfield name="username" label="Username"></s:textfield> <s:password name="userpass" label="Password"></s:password> <s:submit value="register"></s:submit> </s:form> </body> </html>   [/java] Here the developer just created the two text boxes to enter the details such as Username, Password and also created register button. success.jsp [java]<%@ page language="java" contentType="text/html; charset=ISO-8859-1" <pre> pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.o rg/TR/html4/loose.dtd"> <%@ taglib uri="/struts-tags" prefix="s" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> </head> <body> <font color="green"> <h1>Welcome to SPLessons</h1> </font> Hai <s:property value="username"/> </body> </html> [/java] To display the success message that is Welcome to SPLessons. 3. Create the action class. Register.java [java]package com.splessons; import com.opensymphony.xwork2.ActionSupport; public class Register extends ActionSupport { private String username,userpass; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpass() { return userpass; } public void setUserpass(String userpass) { this.userpass = userpass; } public String execute() { return "success"; } }   [/java] Struts 2 comes with an optional action interface (com.opensymphony.xwork2.Action). By implements this interface, it bring some convenient benefits. Here just taken data members and performed GET and SET operations. 5. Create validations in xml file. Register-validation.xml [xml]<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd"> <validators> <field name="username"> <field-validator type="requiredstring"> <message>Name can't be blank</message> </field-validator> </field> </validators> [/xml] Here just written the validation that Name can not be blank while entering the data. struts.xml [xml]<?xml version="1.0" encoding="UTF-8" ?> <pre><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" extends="struts-default"> <action name="register" class="com.splessons.Register"> <resultname="success">success.jsp</result>  <result>index.jsp</result> </action> </package> </struts>   [/xml] Where success is a predefined result type. action element is the sub component of package. It speaks to an activity to be conjured for the approaching request. It has name, class and method attributes. In the event that you don’t determine name property as a matter of course execute() technique will be summoned for the predetermined actiion class. web.xml [xml]<?xml version="1.0" encoding="UTF-8"?> <pre><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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> </web-app> [/xml] The web.xml web application descriptor file represents the core of the Java web application, so it is appropriate that it is also part of the core of the Struts framework. In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests. This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave. 6.Run the program in server, Then the browser display the output as. 7. If the username not given, then the browser display the output as. 8. If the username given as Joshaf, then the browser display the output as.

By using Ajax Validations

shape Description

Struts 2 support Ajax validations, by using the Ajax validations in application then running time page will not be refreshed or reloaded. So, it will make the performance fast. In struts 2, Ajax validation doesn't have stack by default, so one need to create explicitly. Ajax validations is performed by jsonValidator interceptor. jsonValidator found in the jsonValidatorWorkFlowStack. Write the <interceptor-ref> in struts.xml file. struts.xml [xml] <struts> <package name="default"> <action name=" register " class="Action class name"> <interceptor-ref name="jsonValidationWorkFlowStack"/> <result name="success">success.jsp</result> </action> <package> <struts> [/xml]

Summary

shape Key Points

  • Struts 2 Validations - jsonValidation interceptor is utilized to perform AJAX validation.
  • Validateable interface is utilized to create own validating logic's.
  • workflow interceptor is utilized to retrieve data of an error.