Welcome!

AJAX & REA Authors: RealWire News Distribution, Roger Strukhoff, Bob Gourley, Mark O'Neill, Kevin Benedict

Related Topics: AJAX & REA, Java

AJAX & REA: Article

Struts Validations Framework Using AJAX

Real-time data validation is one of the advantages of AJAX technology

Real-time data validation is one of the advantages of AJAX technology. By applying this technology, the struts validation framework will enrich the struts MVC and move the Web application closer to the desktop application.

The validation framework is used to validate fields. There are many ways to do validation on a Web application. It falls into two categories: server-side and client-side. A struts validation framework is one of the best frameworks for a Java-based Web application environment. It can configure the application using server-side validation and employ the error message that renders on the validation process invoked during the request processing time, or it can do client-side validation by using the JavaScript rendered on the requested page.

AJAX is a JavaScript technology that can asynchronously call the server and fetch the XML documents that are so popular lately. One of its uses is real-time data validation.

This article is concerned with enriching the existing struts validation framework with AJAX. A few components, such as a controller, have to be developed to select the validation framework and render the specific format message for the client side and a taglib to handle the error message rendering.

Prerequisites
You'll need a Windows system with Eclipse and the Tomcat application server. Make sure that the MSXML 3.0 ActiveX object is registered on your operating system. You'll also need the Struts library (http://struts.apache.org) and the JDOM library (www.jdom.org) for XML development (see Figure 1 and Figure 2).

Server-Side Scenario
StrustsActionServlet
We have to extend the class from org.apache.struts.action.ActionServlet to get the servletMapping variable that stores the information on how the extension will be formatted for action classes into the action path as a browser address. When the code is added, we have to configure web.xml as a Web application descriptor for the application server.

The web.xml configuration:

...
<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>
...

The StrutsActionServlet Java code looks like this:

public class StrutsActionServlet extends the ActionServlet.
{
public String getServletMapping() {
return this.servletMapping;
}
}

AjaxValidationRequestProcessor
To support the existing Struts framework in the first step, we have to extend the RequestProcessor from the Struts package. We have to customize the request processor because we have to distinguish how we're going to do the validation - by using the existing Struts framework or the AJAX concept - and because we'll be making a contract between the server and client on how to interpret the message. In the message rendering we'll use the XML format, which is a good media messaging format. The definition of the XML format we'll apply is:

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

Description

  • Identity is the ID for the client JavaScript to acknowledge where the message will be placed.
  • Description is the result after the error message rendering from the server side.
First we need to get the servlet mapping configuration from the Web descriptor before moving onto the process mapping. After invoking the process, the application will prepare the instance of the form that inherits from the AjaxForm class. The processing manages AJAX validation and should check to ensure that the request from the client isn't using the struts validation framework. Other processes to perform during the request are process populate for collecting the information sent by the client into the action form, and process validation by using the method from the existing Struts validation framework that already exists in the parent class of AjaxValidationRequestProcessor (TilesRequestProcessor).

The validation process from the TilesRequestProcessor will invoke all the validation based on the struts validation framework and store the action errors into the request. What we need is to parse the action errors into pieces and generate the XML message validation that will be sent to the client side. Since we want to change the behavior of how the validation will be backed, the validation process should check the indicator of the validation framework being used (see Figure 3).

Generate the XML messages using JDOM as the processing engine. As shown in Figure 4, when the process validation is invoked and the condition of the validation framework is equal with the AJAX validation framework, the process will continue to populate the error message and build the XML message validation.

ErrorMessageHandler
This class handles the functionality of the XML message builder. This Java class will be building the XML message based on the identity and description property. After the caller invokes the buildXMLMessage, it will prepare the document and set the root element of the XML message. This class also has an addNextXMLMessage function to add more validation messages into the XML (see Listing 1).

The process method will set the content type of the response as "text/xml" and send the XML message as a string. The function of the process on the AjaxValidationRequestProcessor code will look like Listing 2.

The processValidation method will populate the action errors and construct the message based on the format contract of the XML for the client. The function of processValidation on AjaxValidationRequestProcessor code will be look like:

...
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
Locale locale = (Locale) request.getAttribute(Globals.LOCALE_KEY);
generateXMLMessage(errors, identity, locale, sbXMLMessage);
...

Client-Side Scenario
Build the Taglib Component

  • AjaxJavaScriptLibraryTag: The taglib component to render the JavaScript function at the client side for basic XMLHTTP controller functions.
  • AjaxErrorHtmlRenderTag: The taglib component to render the area of the error message at the JSP page.
Configuring the Taglib Definition
After developing the taglib component, we need to configure the taglib tld file as shown in Listing 3.

Build JSP and Struts Configuration
To simulate the result of the validation processing, we first need to build the presentation layer by incorporating the taglib that we've build. In this case I'm trying to give an example validation by using the validation rules component from Struts, and also the validation that comes from the form itself. Prepare five textboxs under the JSP page. The first to fourth textbox are using the validation rule configuration, and the fifth textbox is using the validate process from the action form. Other than that, we also need a submit button to simulate that after submitting the form, the existing struts validation are still working without AJAX. The user interface will look like Figure 5.

More Stories By Sonny Hastomo

Sonny Hastomo is an IT architect at Sun Microsystems, Indonesia, for the telecommunication industry division. His currently is focusing on providing solution design, sizing, implementation, consulting services, and quality support to customers in their evaluation of their IT challenges.

Comments (9) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
hanan mahmoud 07/27/08 03:39:45 AM EDT

hi all
its realy great article and it helped me to understand validation in ajax better ,i just hope if any one have sample code about that topic because till now i don't know how to find one and also i don't know where to put the code samples in the article so plz help me

Commenter 05/17/06 01:40:52 PM EDT

I just need examples, and I can´t find it here. This article is weak.

SYS-CON Belgium News Desk 05/02/06 03:27:56 PM EDT

Struts Validations Framework Using AJAX
Real-time data validation is one of the advantages of AJAX technology. By applying this technology, the struts validation framework will enrich the struts MVC and move the Web application closer to the desktop application.

SYS-CON Australia News Desk 05/02/06 01:44:38 PM EDT

Real-time data validation is one of the advantages of AJAX technology. By applying this technology, the struts validation framework will enrich the struts MVC and move the Web application closer to the desktop application.

AJAX News Desk 05/02/06 12:55:46 PM EDT

AjaxWorld: Struts Validations Framework Using AJAX
Real-time data validation is one of the advantages of AJAX technology. By applying this technology, the struts validation framework will enrich the struts MVC and move the Web application closer to the desktop application.

Rajesh 05/02/06 12:17:24 PM EDT

The article was really nice.It would have been better if the source code was included.

Thanks

waikit 02/08/06 04:11:11 AM EST

can I have a sample code of the example shown in this article, please

regards

SYS-CON Australia News Desk 01/27/06 02:21:45 PM EST

Real-time data validation is one of the advantages of AJAX technology. By applying this technology, the struts validation framework will enrich the struts MVC and move the Web application closer to the desktop application.

Artem Vasiliev 01/26/06 06:18:56 AM EST

Sonnie, thank you for your article, it brings pretty interesting idea.
It would be great to see some sample application (with source code of course) implementing this approach. I even thought that I would find as a source code for the article, but seems like JDJ doesn't have such practice. Sonnie, can you provide that? It could be an archive hosted somewhere, here or at some free hosting, e.g. http://rapidshare.de/

Cloud Expo Breaking News
Cloud Computing is evolving into a Big Three of Amazon Web Services, Google Cloud, and Microsoft Azure. Cloud 360: Multi-Cloud Bootcamp, being held Nov 4–5, 2014, in conjunction with 15th Cloud Expo in Santa Clara, CA, delivers a real-world demonstration of how to deploy and configure a scalable and available web application on all three platforms. The Cloud 360 Bootcamp, led by Janakiram MSV, an analyst with Gigaom Research, is the first bootcamp that introduces the core concepts of Infrastructure as a Service (IaaS) based on the workings of the Big Three platforms – Amazon EC2, Google Compute Engine, and Azure VMs. Bootcamp attendees will get to see the big picture and also receive the knowledge needed to make the best cloud decisions for their business applications and entire enterprise IT organization.
Scott Jenson leads a project called The Physical Web within the Chrome team at Google. Project members are working to take the scalability and openness of the web and use it to talk to the exponentially exploding range of smart devices. Nearly every company today working on the IoT comes up with the same basic solution: use my server and you'll be fine. But if we really believe there will be trillions of these devices, that just can't scale. We need a system that is open a scalable and by using the URL as a basic building block, we open this up and get the same resilience that the web enjoys.
The Internet of Things is a natural complement to the cloud and related technologies such as Big Data, analytics, and mobility. In his session at Internet of @ThingsExpo, Joe Weinman will lay out four generic strategies – digital disciplines – to exploit emerging digital technologies for strategic advantage. Joe Weinman has held executive leadership positions at Bell Labs, AT&T, Hewlett-Packard, and Telx, in areas such as corporate strategy, business development, product management, operations, and R&D.
SYS-CON Events announced today that DevOps.com has been named “Media Sponsor” of SYS-CON's “DevOps Summit at Cloud Expo,” which will take place on June 10–12, 2014, at the Javits Center in New York City, New York. DevOps.com is where the world meets DevOps. It is the largest collection of original content relating to DevOps on the web today Featuring up-to-the-minute news, feature stories, blogs, bylined articles and more, DevOps.com is where the thought leaders of the DevOps movement make their ideas known.
There are 182 billion emails sent every day, generating a lot of data about how recipients and ISPs respond. Many marketers take a more-is-better approach to stats, preferring to have the ability to slice and dice their email lists based numerous arbitrary stats. However, fundamentally what really matters is whether or not sending an email to a particular recipient will generate value. Data Scientists can design high-level insights such as engagement prediction models and content clusters that allow marketers to cut through the noise and design their campaigns around strong, predictive signals, rather than arbitrary statistics. SendGrid sends up to half a billion emails a day for customers such as Pinterest and GitHub. All this email adds up to more text than produced in the entire twitterverse. We track events like clicks, opens and deliveries to help improve deliverability for our customers – adding up to over 50 billion useful events every month. While SendGrid data covers only abo...
SYS-CON Events announced today that the Web Host Industry Review has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Since 2000, The Web Host Industry Review has made a name for itself as the foremost authority of the Web hosting industry providing reliable, insightful and comprehensive news, reviews and resources to the hosting community. TheWHIR Blogs provides a community of expert industry perspectives. The Web Host Industry Review Magazine also offers a business-minded, issue-driven perspective of interest to executives and decision-makers. WHIR TV offers on demand web hosting video interviews and web hosting video features of the key persons and events of the web hosting industry. WHIR Events brings together like-minded hosting industry professionals and decision-makers in local communities. TheWHIR is an iNET Interactive property.
SYS-CON Events announced today that O'Reilly Media has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. O'Reilly Media spreads the knowledge of innovators through its books, online services, magazines, and conferences. Since 1978, O'Reilly Media has been a chronicler and catalyst of cutting-edge development, homing in on the technology trends that really matter and spurring their adoption by amplifying "faint signals" from the alpha geeks who are creating the future. An active participant in the technology community, the company has a long history of advocacy, meme-making, and evangelism.
SYS-CON Events announced today that Verizon has been named “Gold Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Verizon Enterprise Solutions creates global connections that generate growth, drive business innovation and move society forward. With industry-specific solutions and a full range of global wholesale offerings provided over the company's secure mobility, cloud, strategic networking and advanced communications platforms, Verizon Enterprise Solutions helps open new opportunities around the world for innovation, investment and business transformation. Visit verizonenterprise.com to learn more.
SYS-CON Events announced today that TMCnet has been named “Media Sponsor” of SYS-CON's 15th International Cloud Expo®, which will take place on November 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA. Technology Marketing Corporation (TMC) is the world's leading business to business and integrated marketing media company, servicing niche markets within the communications and technology industries.
"In my session I spoke about enterprise cloud analytics and how we can leverage analytics as a service," explained Ajay Budhraja, CTO at the Department of Justice, in this SYS-CON.tv interview at the 14th International Cloud Expo®, held June 10-12, 2014, at the Javits Center in New York City. Cloud Expo® 2014 Silicon Valley, November 4–6, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading Cloud industry players in the world.
“We are starting to see people move beyond the commodity cloud and enterprises need to start focusing on additional value added services in order to really drive their adoption," explained Jason Mondanaro, Director of Product Management at MetraTech, in this SYS-CON.tv interview at the 14th International Cloud Expo®, held June 10-12, 2014, at the Javits Center in New York City. Cloud Expo® 2014 Silicon Valley, November 4–6, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading Cloud industry players in the world.
"We are automated capacity control software, which basically looks at all the supply and demand and running a virtual cloud environment and does a deep analysis of that and says where should things go," explained Andrew Hillier, Co-founder & CTO of CiRBA, in this SYS-CON.tv interview at the 14th International Cloud Expo®, held June 10-12, 2014, at the Javits Center in New York City. Cloud Expo® 2014 Silicon Valley, November 4–6, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading Cloud industry players in the world.
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity. In his session at Internet of @ThingsExpo, Mac Devine, Distinguished Engineer at IBM, will discuss bringing these three elements together via Systems of Discover.
The Internet of Things promises to transform businesses (and lives), but navigating the business and technical path to success can be difficult to understand. In his session at 15th Internet of @ThingsExpo, Chad Jones, Vice President, Product Strategy of LogMeIn's Xively IoT Platform, will show you how to approach creating broadly successful connected customer solutions using real world business transformation studies including New England BioLabs and more.
All too many discussions about DevOps conclude that the solution is an all-purpose player: developer and operations guru, complete with pager for round-the-clock duty. For most organizations that is not the way forward. In his session at DevOps Summit, Bernard Golden, Vice President of Strategy at ActiveState, will discuss how to achieve the agility and speed of end-to-end automation without requiring an organization stocked with Supermen and Superwomen.