JEE Series: Struts 2 Tags and Client-Side Validation

This post concludes the example from the previous article. Today, we take a closer look at the client-side, namely the use of tags and how to perform an efficient input validation.

The whole example can be downloaded from github.

At this point we have all the configuration in place and we are ready to register a new user. A registration form is a JSP page. It's worth mentioning that there is no hand-written HTML. Instead we make use of Struts tags. That eliminates the risk of errors preventing framework's core functionality, such as input validation.
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <%@ taglib prefix="s" uri="/struts-tags" %>  
 <!DOCTYPE html>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">      
     <link rel="stylesheet" type="text/css" href="css/main.css">  
     <title>New User</title>      
   </head>  
   <body>  
     <h1>Registration Form</h1>  
     <s:form action="register" method="post" validate="true">  
       <s:textfield label="Username" name="user.name" />  
       <s:textfield label="Email" name="user.email" />  
       <s:password label="Password" name="user.password" />  
       <s:submit />  
     </s:form>  
   </body>  
 </html>  
Notice the validate attribute in the form tag. It enables client-side validation.  What happens is the framework adds javascript validation to your page. Validation rules will be an exact match of what is specified in the User class.

No roundtrip to the server happens until the validation is a pass:

Struts adds its own javascript libraries:

Work around the javascript layer (simply disable javascript in the browser) and the app falls back to the server-side validation:

Once all the input is as expected the RegistrationAction redirects to the registration confirmation page:
 <%@page contentType="text/html" pageEncoding="UTF-8"%>  
 <%@ taglib prefix="s" uri="/struts-tags" %>  
 <!DOCTYPE html>  
 <html>  
   <head>  
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
     <link rel="stylesheet" type="text/css" href="css/main.css">  
     <title>Registration Success</title>  
   </head>  
   <body>  
     <h1>Congrats <s:property value="user.name" />!</h1>  
     <p>A confirmation email has been sent to <b><s:property value="user.email" /></b></p>  
     <s:a href="register">Home</s:a>      
   </body>  
 </html>  
Once again, we make use of Struts tags in order to access properties of the new User.

That concludes the brief intro into Struts 2. Next time we start with another web technology from the JEE stack - JavaServer Faces. Stay tuned.

Source Code