http://www.developer.com/

Back to article

Verifying User Input Using JSP Tag Libraries


December 11, 2003

In any Web-based application where program logic requires information submitted by the user to be validated, the creators of the application can check data in two ways. The first method is to do validation on the client side, even before anything is submitted to the server. Usually, this is done using JavaScript running in the client's Internet browser. While the form is being submitted, the script will check all required fields and pop up error messages in case of any discrepancies. The second way is to do validation on the server side, before performing any operation with the data, using the technology that the application server supports.

Server-side verification puts more strain on the server, but gives programmer more control, and guarantees that data will be checked. Client-side verification can easily be circumvented by the user (by disabling JavaScript), therefore allowing unchecked information to be submitted, but could be faster, because users don't have to post and get pages from the server.

Currently, more and more online applications rely on server-side validation, mainly because it guarantees checking and improves application security, but also because server hardware and software performance have significantly improved in recent years, and because it allows for greater flexibility of the program and sometimes is easier to implement.

In this article, I will describe a unique way of using a Java JSP tab library for server-side verification, and briefly describe the creation of JSP tags. The examples will build upon a Web application from my previous article "Applying MVC to web-based applications with JSP views"—a simple project that displays weather information after users submit a ZIP code or city name. The application followed Model-View-Controller (MVC) architecture and used the Tomcat application server.

Validation Process

In an enterprise-level application, data validation is a required part of the security process. Not only do applications have to catch empty or partial fields, but also have to guard against erroneous entries. If data is submitted into a RDBMS store or any other persistent storage and is used in SQL statements, users can accidentally (or purposely) submit bad data that can result in invalid SQL statements. A malicious user can even post escape strings or put specific data in the submit form to perform an operation not originally designed by the Web application developer. For example, they can delete a row or table from the database or get any information they want.

The JSP pages where I've implemented validation are "Views" in the MVC design, part of the online weather program. Each JSP view either submits or displays data. When form with a ZIP code or city name is submitted, information is posted to the server, where a Controller Servlet object performs an action based on a specific action key parameter from the JSP, and redirects to the next View. But, more detail on this later; let's look at the workings of JSP tags.

JSP Tags

You can think of the JSP tag as a custom action that is performed by Java code running on the server. In the JSP, a tag looks like a standard HTML tag except its logic is not executed on the client side, but on the server side as part of the Servlet into which a JSP is converted. Each tag is encapsulated in a separate class and its name and parameter attributes are indicated in a special deployment descriptor file with a tld extension. This file should be placed under the web-app directory WEB-INF in your application server, and indicated for use in JSP with a <%@taglib ... %> directive and in a web.xml file. When a JSP engine encounters a custom tag, it checks to see whether it knows where that the tag class is, and if it does, it executes the corresponding code. The tag classes are usually put into a jar file and placed under the lib directory under WEB-INF.

Ex. ..\WEB-INF\mytags.tld - deployment descriptor file

Ex. ..\WEB-INF\lib\mytags.jar tag library (or a full directory structure)

To show how to use tags for validation, I've created a custom JSP tag to validate the ZIP code field, named notValidZip. Tags, however, can perform any action, such as HTML formatting, field manipulation, or even database queries. For other checks, I use a tag library from Coldbeans Software (http://www.servletsuite.com), which is free for non-commercial use, and has extremely practical tags for the validation of HTML form fields. If you need to use tags on a commercial site, you can always write your own or purchase them.

Here is a part of the deployment descriptor file validtag.tld that deals with my notValidZip tag:

<tag>

<name>notValidZip</name>

<tagclass>com.cj.valid.notValidZip</tagclass>

<bodycontent>JSP</bodycontent>

<info>testszip code</info>

 

<attribute>

<name>value</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

 

<attribute>

<name>length</name>

<required>false</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

</tag>

It indicates that the name is notValidZip, its code is in the com.cj.valid.notValidZip class, and it has two attributes, one required and one optional.

To let the Web application know that I'm including a custom tag library, I added its information to the web.xml deployment descriptor file. Here is the code that does it:

<taglib>

     <taglib-uri>/WEB-INF/validtag.tld</taglib-uri>

     <taglib-location>/WEB-INF/validtag.tld</taglib-location>

</taglib>

And, finally, to include this tag library in the JSP, I added this line at the beginning on my JSP page:

<%@ taglib uri="/WEB-INF/validtag.tld"prefix="valTag" %>

Now, I can use any tag from that package by writing its <prefix> : <tag name>; for example:

<valTag:notValidZip value="<%=request.getParameter(\"ZIP\")%>">

 <!-- body -->

</valTag:notValidZip>

Tags usually have a body and optional attributes.

<valTag:tagnameattribute1="value1" attribute2="value2">

  <!-- body -->

</valTag:tagname>

But some tags may not have a body; for example <valTag:tagname />.

You can write any prefix you want when defining a tag library, but tag names must match names in the tld file.

As I said, the actual verification logic is done in a Java class also called "notValidZip", located in the tag lib jar file. The tag class extends the abstract TagSupport classes and imports the javax.servlet.jsp.JspException, javax.servlet.jsp.tagext. Tag, and javax.servlet.jsp.tagext.TagSupport classes. The main action logic is in the doStartTag() method, which is called when the JSP engine encounters my new tag.

The integer code returned by this method tells the JSP engine whether or not it should do the body of the tag. See Listing 1 at the end of this article.

So, let's review. First, you write the tag class, put it in the jar file under web-application 'lib' directory, create a deployment descriptor file for the tag, update the web.xml file with its location information, and use it in your JSPs by including it with taglib directive. If I need to do my ZIP code verification in multiple places, all I have to do is include my tag in multiple pages. See Listing 2.

JSP Views with Validation

Usually to add validation, programmers need a separate JSP page that looks like original form page, but has error messages and is displayed (redirected to) by the server in case the form fields have problems. I simply added error logic in the original JSP page. When the form is displayed for the first time, error checking is not done. On the submit action, the form is submitted onto itself, fields are validated using JSP tags (on the server side, JSPs are compiled into Servlets), and if everything is correct, data is posted to the main Controller Servlet. If not, users will see an error message in the same JSP.

In the JSP page, I have a Java scriplet that creates a boolean flag variable "validate", and sets it to true if there is a "validate" parameter submitted to this JSP.

<% boolean validate = ("true".equals((String)request.getParameter("validate"))); %>

Based on the value of this Boolean variable, JSP will do validation with my tag. When the page is loaded for the first time, this variable is false and validation is not done.

To submit the page into itself and then redirect it to the main Controller Servlet, I changed the form action to point to <%=request.getRequestURI()%> and added the default JSP forward tag <jsp:forward page="../MainServlet" />.

When the user submits the form, it posts all values onto the same JSP, sets the validate variable to true, does checking using tags, and if data is approved, JSP forwards all values to the Controller Servlet.

If there is a problem, the tag body will execute and tell JSP to resubmit values onto itself again, showing new (or different) error messages depending on the errors. Please note that another Boolean variable "success" is set to false inside of the tag body. This variable is initially set to true and is there only to check if any tag body has been executed. This makes sure the form is forwarded only if both the "validate" and "success" variables are true. See Listing 2.

In a situation where you have multiple fields being validated, error massagers from the tag bodies will show for incorrect fields, decreasing every time user makes corrections and resubmits.

Wrong ZIP code result page:

Correct ZIP code result page:

Conclusion

The extra logic that I put in JSP to perform validation in the same page and combined it with use of tags allowed me to create a simple and highly reusable solution for server-side data verification, without multiple JPS or Servlets doing it. One tag is all that is necessary to validate any kind of field, and you can have specific tags for different field types; for instance, e-mail, phone, or integer-only fields. This design extends the JSP view layer of the Model-View-Controller project and by using it I also increased the separation of the presentation from the logic layers. Web designers and developers using JSP tags for validation don't have to change any code in JSP if the tag code is modified; furthermore, they don't even have to know how it validates or any Java syntax it uses. All they have to do is simply include an HTML-like tag in their JSP page.

Download source code here.

Code Listings

Listing 1

public int doStartTag() throwsJspException {

// retrun code of 1 will cause tagbody to execute

if (value == null)

returnthis.EVAL_BODY_INCLUDE;//check if we have zip code

if(value.equals(null))

//check ifvalue is not null

returnthis.EVAL_BODY_INCLUDE;

if(value.length() ==5) {

//hasto be an integer! short case of zip code xxxxx

try{

Integer.parseInt(value);

return this.SKIP_BODY;

} catch (NumberFormatException e){

return this.EVAL_BODY_INCLUDE;

}

} else if (value.length() == 10) {

// long case of Zip code xxxxx-xxxx

Stringpart1 = value.substring(0, 5);

Stringdash = value.substring(5, 6);

Stringpart2 = value.substring(6);

if(!dash.equals("-"))

return this.EVAL_BODY_INCLUDE;

try {

Integer.parseInt(part1);

Integer.parseInt(part2);

return this.SKIP_BODY;

} catch (NumberFormatException e){

return this.EVAL_BODY_INCLUDE;

}

}

returnthis.EVAL_BODY_INCLUDE;// all other cases

Listing 2

<FORM action="<%=request.getRequestURI()%>" method="post">

<TABLE border="1">

<input type="hidden" name="ACTIONKEY" value="WeatherAction.viewByZip">

<input type="hidden" name="REDIRECTKEY" value="weather_data">

<input type="hidden" name="validate" value="true">

<TBODY>

<TR>

<TD><font face=Arial size=2>Zip:</font></TD>

<TD>

<% if (validate) { %>

<valTag:notValidZipvalue="<%=request.getParameter(\"ZIP\")%>">

<!-- do something if field is empty -->

<font color=red face=arial size=2>

Please enter valid Zip Code

</font><br>

<% success=false; %>

</valTag:notValidZip>

<% } %>

<INPUT type="text" name="ZIP" value="<%=((validate)?request.getParameter("ZIP"):"")%>">

<% if (success && validate){ %>

<jsp:forward page="../MainServlet" />

<% } %>

</TD>

</TR>

<TR>

<TD></TD>

<TD><INPUT type="submit" name="view" value="View"></TD>

</TR>

</TBODY>

</TABLE>

</FORM>

Listing 3

About the Author

Vlad Kofman is a System Architect working on projects under government defense contracts. He has also been involved with enterprise-level projects for major Wall Street firms and the U.S. government. His main interests are object-oriented programming methodologies and design patterns.

References

"Java Servlet Technology" by Stephanie Bodoff
http://java.sun.com/webservices/docs/1.0/tutorial/doc/Servlets.html

"Servlets and JavaServer Pages (JSP) 1.0: A Tutorial"
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/

JSP Tag Libraries
Gal Shachor, Adam Chace, Magnus Rydin
May 2001, Manning Publications Co.
ISBN 193011009X

"Chapter 3: Developing your first tags"
http://javaboutique.internet.com/resources/books/jsp_taglib/

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date