Struts validation framework using AJAX--real-time data validation is a big advantage of Ajax technology

Source: Internet
Author: User
Tags locale prepare advantage
Struts validation framework using AJAX--real-time data validation is a big advantage of Ajax technology

Author: Sonny Hastomo

Real-time data validation is one of the great advantages of Ajax technology. By applying this technology, the Struts validation framework enhances struts MVC and makes Web applications closer to desktop applications.

This validation framework is used to validate fields. There are many ways to validate on a Web application. These methods can be divided into two categories: server-side methods and client methods. The Struts validation framework is one of the best frameworks for a java-based Web-application environment. It is able to configure the application by using server-side validation and error messages, which are rendered on the calling verification process when processing the request, and are capable of client-side validation by using the JavaScript rendered on the request page.

Ajax is a JavaScript technology that makes it possible to call servers asynchronously and get XML documents, a document that has been very popular recently. One of its uses is real-time data validation.

This article focuses on using AJAX to enhance the existing struts validation framework. Several components, such as a controller, must be developed to select a validation framework and to render messages in a particular format (for clients) and tag libraries (handling error message rendering). Necessary Conditions

Requires a Windows system with Eclipse and Tomcat application servers. Make sure that the MSXML 3.0 ActiveX object has been registered with the operating system. The Struts Library (http://struts.apache.org) and the Jdom Library (www.jdom.org) are also required for XML development (see Figure 1 and Figure 2).

server-side Scenarios Strustsactionservlet

We have to extend the class from Org.apache.struts.action.ActionServlet to get the servletmapping variable, which stores information about how to format the extension as a browser address form for the action class. When adding code, we must configure Web.xml as the application server's Web application descriptor.

The Web.xml configuration is as follows:

...
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>net.sf.struts.servlet.StrutsActionServlet</servlet-class>
...
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


public class Strutsactionservlet extends the Actionservlet.
{
Public String getservletmapping () {
return this.servletmapping;
}

Ajaxvalidationrequestprocessor

To support the existing struts framework in the first step, we must extend the requestprocessor from the Struts software package. We have to customize this request processor because we have to identify how it will be validated (by using the existing Struts framework or AJAX concepts), as we will develop a contract between the server and the client about how to interpret the message. In the context of message rendering, we will use XML format, which is a good media messaging format. The XML format that we will apply is defined as:

XML Format

XML Format
<?xml version= "1.0" encoding= "UTF-8"?>
<message>
<identity name=messageareaid>
<description>
Messagevalue
</description>
</identity>

DescriptionIdentity is the ID that client JavaScript uses to understand where the message will be placed. Description is the result of rendering an error message on the server side.

First we need to get the servlet mapping configuration from the Web descriptor before proceeding with the process mapping. When this process is invoked, the application prepares the form instance, which inherits from the Ajaxform class. This processing manages AJAX validation and should be checked to determine that requests from clients do not use the Struts validation framework. Other processes that are executed during the request process are process fills (used to collect information sent by the client to the Action form) and process validation (by using the existing Struts validation framework already exists in the Ajaxvalidationrequestprocessor the method in the parent class Tilesrequestprocessor).

The validation process from Tilesrequestprocessor invokes all validation based on the struts validation framework and stores action errors to the request. We need to analyze the action errors carefully and generate XML message validation, which will be sent to the client. Because we want to change the behavior that supports validation, the validation process should check the indicator of the validation framework used (see Figure 3).

Generates an XML message using Jdom as the processing engine. As shown in Figure 4, if process validation is invoked and the condition of the validation framework is equivalent to an AJAX validation framework, the process continues to populate the error message and build XML message validation.

Errormessagehandler

This class handles the functionality of the XML Message Builder. This Java class constructs an XML message based on the identity and description properties. After the caller invokes Buildxmlmessage, it prepares the document and sets the root element of the XML message. This class also has a addnextxmlmessage function to add more validation messages to the XML (see Listing 1).

  Listing 1

...
public void Buildxmlmessage () throws Parserconfigurationexception {

Initiate document Builder to prepare the media of XML message
This.rootelement = new Element (constant_message);

Addnextxmlmessage ();

}
...
public void Addnextxmlmessage () throws Parserconfigurationexception {

Creating the XML message based on format above
Element identityelement = new Element (constant_identity);

Identityelement.setattribute (Constant_name, this.identity);

Element descriptionelement = new element (constant_description);
Descriptionelement.addcontent (this.description);
Identityelement.addcontent (descriptionelement);
Rootelement.addcontent (identityelement);
}

This process method sets the content type of the response to "text/xml" and sends the XML message as a string. The process functions on the Ajaxvalidationrequestprocessor code are shown in Listing 2.

Listing 2

public void process (HttpServletRequest req, HttpServletResponse resp)
Throws IOException, Servletexception
{
if (Request.getparameter (CONSTANT_VALIDATION_FRAMEWORK_ARG)!= null)
{
...
This.processvalidate (req, RESP, form, mapping);
Response.setcontenttype (Constant_xml_content_type);
Response.getwriter (). Write (sbxmlmessage.tostring ());
Response.flushbuffer ();

}
} else
{
Super.process (req, resp);
}
}
The Processvalidation method fills the

Action error, and constructs the message based on the client-oriented XML format contract. The Processvalidation function on the Ajaxvalidationrequestprocessor code looks like this:

...
Actionerrors errors = (actionerrors) request.getattribute (Globals.error_key);
Locale Locale = (Locale) request.getattribute (Globals.locale_key);
Generatexmlmessage (Errors, identity, Locale, sbxmlmessage);

Client Scenarios Building Tag Library componentsAjaxjavascriptlibrarytag: This tag library component renders JavaScript functionality on the client to achieve basic XMLHTTP controller functionality. Ajaxerrorhtmlrendertag: This tag library component renders the error message area in the JSP page. Configure Tag Library definition

After developing the tag library component, we need to configure the tag library TLD file shown in Listing 3.

Listing 3

<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>ajaxLib</shortname>

<tag>
<name>library</name>
<tagclass>net.sf.ajax.taglib.ajaxjavascriptlibrary
</tagclass>
<bodycontent>JSP</bodycontent>
</tag>

<tag>
<name>error</name>
<tagclass>net.sf.ajax.taglib.ajaxerrorhtmlrender
</tagclass>
<bodycontent>JSP</bodycontent>
<attribute>
<name>property</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>event</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

</taglib>
building JSP and Struts configuration

To simulate the results of validation processing, we first need to build the rendering layer by merging the tag libraries we have built. In this example, I tried to give an example validation (by using the validation rule component from struts) and from the form itself. Prepare a text box under five JSP pages. The first to fourth text box uses the validation rule configuration, and the fifth text box uses the validation process from the action form. In addition, we need a submit button to simulate it after submitting the form, and the existing struts validation still works without Ajax. The user interface looks as shown in Figure 5.

Building actions and action forms

To get the struts action, we go to the JSP that has been built. This action code looks like this:

Public Actionforward Execute (...) {
Return Mapping.findforward ("Success");
}

If the input is blank, the Action form code verifies the Requiredtext property. Keep in mind that you want to extend this form from the Ajaxform class. The validation method for the action form is as follows:

Public actionerrors Validate (...) {
Actionerrors errors = new Actionerrors ();
if (Stringutils.isempty (This.requiredtext)) {
Errors.add ("Requiredtext", New Actionerror ("Error.required.input"));
}
Request.setattribute (Globals.error_key, errors);

apply struts validation rules

Configuring a Struts validation rule (for example, minimum length, maximum length, e-mail, and modal text) is applied to the input object of the client, and the configuration is similar to listing 4.

Listing 4

<field property= "Paterntext"
depends= "Required,mask" >
<arg0 key= "Label.paterntext"/>
<var>
<var-name>mask</var-name>
<var-value>^[0-9]{3}-[0-9]{2}___FCKpd___8lt;/var-value>
</var>
</field>
<field property= "MinLength"
depends= "MinLength" >
<arg0 key= "Label.minlength"/>
<arg1 key= "${var:minlength}" resource= "false"/>
<var>
<var-name>minlength</var-name>
<var-value>5</var-value>
</var>
</field>

<field property= "MaxLength"
depends= "MaxLength" >
<arg0 key= "Label.maxlength"/>
<arg1 key= "${var:maxlength}" resource= "false"/>
<var>
<var-name>maxlength</var-name>
<var-value>5</var-value>
</var>
</field>

<field property= "Email"
depends= "Email" >
<arg0 key= "Label.email"/>
</field>
Validating processing Flow

First the client initializes the XMLHTTP component to execute the request to the server, and then the URL parameter is sent to the server when the user trigger starts to build. After the build parameters are complete, the client connects the Oneadystatechange XMLHTTP event to listen for the response from the server side. When a response is received, the client begins parsing the XML validation message and places the message in the correct area (see Figure 6).

If the request is accepted by the server, the server starts checking the parameters of the AJAX validation condition and processes the validation. When completed, the specific error associated with the user input object is filtered out from the generated Error object. After the filtering process is complete, an XML message is generated and sent back to the client (see Figure 7).

Concluding remarks

In this article, we build a controller that receives asynchronous requests from the client and merges the struts validation process to produce an action Error object. After the error object is generated and an XML message is generated that returns the client as a reply to indicate an error message, the specific input object being validated is filtered (see Figure 8 and Figure 9).

Original source:http://jdj.sys-con.com/read/171472.htm

Author Introduction
Sonny Hastomo is a product development consultant for Sigma Cipta Caraka's electronic delivery channel team for bank Solutions, and he is currently focused on integration and connectivity with legacy applications from os/400 and AIX operating systems.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.