Validating user input using the JSP tag library

Source: Internet
Author: User
Tags commit include integer tag name tagname valid zip domain
Js


In any web-based application, the program logic requires the user to submit information that needs to be validated, and the creator of the application can detect the data in two ways. The first approach is to validate on the client, even before the information is submitted to the server. Typically, this checksum can be done using JavaScript that runs in the client's Internet browser. Although the table will be submitted, the script will still check all the requested domains and, if not, eject the error message. The second approach is to validate on the server side. Use the technology supported by the application server to complete the checksum before performing any operations on the data.

Server-side checksums make the server more nervous, but give programmers more control and ensure that the data will be detected. Client-side checksums are easily bypassed by the user (by making JavaScript unavailable), so allowing the submission of unchecked information can make it faster because users do not have to transfer pages to the server or get pages from the server.

At present, more and more online applications rely on server-side checksums, the main reason is that it guarantees detection and improves the security of the application, another reason is that server hardware and software performance has improved significantly in recent years, and one reason is that it takes into account the greater flexibility of the program and is often easy to implement.

Directory

Validation process
JSP tags
JSP view with check capability
Conclusion
Code List

In this article, I'll discuss the only way to use the Java JSP Tag library for server-side checksums, and briefly describe the creation of a JSP tag library. I'll build an example of a Web application described in my previous article "Applying MVC to web-based applications with JSP views"-a simple project that displays weather information after a user submits a zip code or a city name. The Web application adheres to the Model-view-controller (MVC) structure and uses the Tomcat application server.

Validation process

In enterprise applications, data validation is a necessary part of a security process. Applications must not only capture airspace or local domains, but they must also prevent errors. If the data is submitted to an RDBMS storage or any other persistent memory, and is already in use in an SQL statement, the user is able to submit (or deliberately) commit bad data that results in an invalid SQL statement. A malicious user can even pass an escape string or enter special data into the submission form, enabling them to perform any operation that the Web application developer did not originally design. For example, they can delete rows or tables from the database, or get the information they want.

I have completed the checksum JSP page in the MVC design of the "views", while the MVC design is part of the online weather program. Each JSP view either submits data or displays data. When a table with zip code or city name is submitted, the information is passed to the server. On the server, the Controller servlet object performs an operation on the basis of a special operation-from the key parameter of the JSP-and then redirects to the next view. More details I will discuss later; Now let's look at how JSP tags work.

JSP tags

You can consider a JSP tag as a custom action that can be executed by Java code running on the server. In a JSP, the tag looks like a standard HTML tag, but its logic does not execute on the client, but rather as part of the servlet converted as a JSP on the server side. Each tag is encapsulated in a separate class, and his name and parameter attributes are displayed in a special configuration descriptor file with a TLD extension. The file should be placed under the Web application directory web-inf your application server and use% @taglib in the JSP.% instruction displays the file, which is displayed in the Web.xml file. When the JSP engine encounters a custom tag, it detects whether it knows where the tag class is, and if so, executes the appropriate code. Tag classes are usually placed inside 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 the tag for validation, I created a custom JSP tag to validate the ZIP code domain named Notvalidzip. Tags can perform any action, such as HTML formatting, domain operations, or even database queries. For other tests, I used a tag library from Coldbeans Software (http://www.servletsuite.com) and a very real tag for validating HTML table fields. Coldbeans software can be used for non-commercial use free of charge. If you need to use tags on a business site, you can write or purchase them yourself.

Here is a configuration descriptor file Validtag.tld, which handles my notvalidzip tags:

<tag>
<name>notValidZip</name>
<tagclass>com.cj.valid.notValidZip</tagclass>
<bodycontent>JSP</bodycontent>
<info>tests Zip 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>

Display the result as: its name is Notvalidzip, its code in the Com.cj.valid.notValidZip class, he has two attributes, a property required, an attribute alternative.

To let the Web application know that I included a custom tag library, I added the information for this tag library to the Web.xml configuration descriptor file. Here's the code:

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

Finally, to include this tag library within the JSP, I added this line of code at the top of my JSP page:

<%@ taglib uri= "/web-inf/validtag.tld" prefix= "Valtag"%>

Now, by writing a tag prefix, you can use any tag from that package, for example:

<valtag:notvalidzip value= "<%=request.getparameter (\" zip\ ")%>" >
<!--body-->
</valTag:notValidZip>

Tags usually have an individual and an alternate attribute.

<valtag:tagname attribute1= "value1" attribute2= "value2" >
<!--body-->
</valTag:tagname>

But some markers may not have a body;

<valtag:tagname/>

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

As I said, the real validation logic is done in Java classes, and this Java class is also called "notvalidzip" and placed inside the tag library jar file. The tag class extends the abstract TagSupport class and introduces the Javax.servlet.jsp.JspException, Javax.servlet.jsp.tagext. tags and javax.servlet.jsp.tagext.TagSupport classes. The main action logic is within the doStartTag () method. This method is invoked when the JSP engine encounters my new tag.

The integer code returned by the doStartTag () method tells the JSP engine whether it should manipulate the tagged body. See Listing 1 at the end of this article.

Now let's summarize. First, you write the tag class, place it in a jar file in the Web application ' lib ' directory, create a configuration descriptor file for the tag, update the Web.xml file with its location information, and then include it in your JSP using the TAGLIB directive, and you can use it in your jsps. If I need to do zip code verification in more than one place, I'll just include my tags in multiple pages. See Listing 2.

JSP view with check capability

Typically, to add checksums, the programmer needs a separate JSP page that looks like an original form page, displays an error message if there is a problem with the table field, and is displayed (redirected) to the page by the server. I only added the error logic to the original JSP page. The first time the table is displayed without error detection. In the commit action, the form is submitted to himself, and the JSP tag verifies the domain (on the server side, JSPs is compiled into servlets), and if everything is correct, the data is passed to the main controller Servlet. Otherwise, the user can see the error message in the same JSP.

In the JSP page, I have a Java scriplet that can create the logical tag variable "validate" and, if there is a "validate" parameter submitted to the JSP, its value is true.

<% Boolean validate = ("true". Equals ((String) request.getparameter ("Validate")); %>

Based on this logical variable value, the JSP uses my markup for validation. When the page is first loaded, this variable is false and does not require a checksum.

To submit the page to itself, and then redirect it to the main controller Servlet, I modify the table action to point to

<%=request.getrequesturi ()%>

, and the default JSP advances to the tag

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

When the user submits the form, he passes all the values to the same JSP, sets the value of the variable validate to True, detects the tag used, and if the data is approved, the JSP passes all the values to the controller Servlet.

If there is a problem, the tag body executes and tells the JSP to resubmit the value to itself, and then displays the new (or different) error message based on the difference in the error. Note that another variable "success" in the tag body is also set to false. This variable is set to True at the beginning and only checks whether any markup bodies have been executed. This ensures that the table is passed only if both the "Validate" and "success" variables are true. See Listing 2.

If you have multiple domains that need to be validated, error messages from the tag body will display incorrect fields, which reduces the number of user corrections and resubmit.

The wrong ZIP code produces the following page:

The correct ZIP code produces the following pages:

Conclusion

The additional logic I enter into the JSP can perform a checksum operation in this JSP page, combining the logic with the tag to create a simple and very reusable solution for server-side data validation without using multiple JSPs or servlets. Verify that any type of domain as long as a tag, you can have a different domain type of special tags, such as e-mail, phone, or only integers of the domain. This design extends the JSP view layer of the Model-view-controller project, and I can use it to enhance the degree of separation of images from the logical layer. If the markup code changes, web designers and developers using JSP tag checksums do not have to modify any of the code in the JSP, and they do not have to know how it is validated or what Java syntax he uses. They can just include HTML-like tags in their JSP pages. "Original text" "Download Source Code"

Code List

Listing 1

public int doStartTag () throws Jspexception {
Retrun code of 1 would cause tag body to execute
if (value = = null)
return this. Eval_body_include; Check if we have zip code
if (value.equals (null))
Check if value is not null
return this. Eval_body_include;
if (value.length () = = 5) {
Has to is 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
String part1 = value.substring (0, 5);
String dash = value.substring (5, 6);
String part2 = 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;
}
}
return this. 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:notvalidzip value= "<%=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 who engages in projects in government defense contracts. He has also been involved in major Wall Street firms and corporate-level projects in the U.S. government. His main interest is in object-oriented programming methods and design patterns.




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.