Spring DWR Validation

This article is a sequel to article on Spring-DWR Integration

In this section, we are going to discuss about how to do validation using DWR in Spring application.

In Server side validation, generally we will submit a form to get the individual fields validated. Using DWR (which is an Ajax framework), we are going to validate each field instantly, without the need to submit the form .

We are going to use the same example as in the Spring Validation article.

Consider the following example. We are going to validate a JSP with three fields ( name, age and email) using DWR.

Have a look at the ValidatePage.jsp

ValidatePage.jsp

<%@ page contentType="text/html;charset=UTF-8" %>  
<%@ page pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<fmt:setBundle basename="messages"/>

<html>

<head>
        <title> Validation Demo - TechDive.in</title>
</head>

<script type="text/javascript"
        src="<c:url value='/dwr/engine.js'/>">
</script>

<script type="text/javascript"
        src="<c:url value='/dwr/util.js'/>">
</script>

<script type="text/javascript"
        src="<c:url value='/dwr/interface/validateService.js'/>">
</script>

<script type="text/javascript">
var fieldNameVal ;
function validateField(fieldName) {
       
        fieldNameVal=fieldName.name;

        if(fieldName.name==document.getElementById('name').name)
        {
                var ct = document.getElementById('name').value;
                validateService.validateName(ct,postCommentHandler);
                return;
        }
        else if(fieldName.name==document.getElementById('age').name)
        {
                var ct = document.getElementById('age').value;
                validateService.validateAge(ct,postCommentHandler);
                return;
        }      
        else if(fieldName.name==document.getElementById('email').name)
        {
                var ct = document.getElementById('email').value;
                validateService.validateEmail(ct,postCommentHandler);
                return;
        }      
}

//AJAX Callback Function
function postCommentHandler(attrs) {
        var message='';
        var st = document.getElementById(fieldNameVal+'Id');
        if(attrs == null)
        {
          //alert("attrs is null ");
        }
        else
        {
        if(attrs=="error_empty_value")
         message = '<fmt:message key="error_empty_value"/>';
        else if(attrs=="error_negative_age")
                var message = '<fmt:message key="error_negative_age"/>';
                else if(attrs=="error_too_large_age")
                        var message = '<fmt:message key="error_too_large_age"/>';
                          else if(attrs=="error_invalid_email")
                                        var message = '<fmt:message key="error_invalid_email"/>';
        }
        st.innerHTML = message;
}

function callOnLoad(init) {
    if (window.addEventListener)
    {
        window.addEventListener("load", init, false);
    }
    else if (window.attachEvent)
    {
        window.attachEvent("onload", init);
    }
    else
    {
        window.onload = init;
    }
}
</script>

<body>

<h1>DWR Validation Demo - TechDive.in - Main Form</h1>

<form:form method="post" commandName="cmdData">

    <p>Enter Name : <form:input path="name" onblur="javascript:validateField(this)" /> </p>
    <h2><font color="#2c770b"><span id="nameId" /></font></h2>
   
    <p> Age : <form:input path="age" onblur="javascript:validateField(this)" /></p>
    <h2><font color="#2c770b"><span id="ageId" /></font></h2>
   
     <p> Email : <form:input path="email" onblur="javascript:validateField(this)" /></p>    
    <h2><font color="#2c770b"><span id="emailId" /></font></h2>
       
</form:form>

</body>

</html>

In the above JSP file, each field is validated when it loses focus ie., onBlur() Java Script method is called to validate the method using DWR.

Here is the DWR validation class, which contains three methods to validate the fields.

package in.techdive.spring.dwr;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ValidateService
{
        public ValidateService()
        {
        }

        public String validateName(String name)
        {
                System.out.println("name is ..." + name);

                if (name == null || name.equalsIgnoreCase(""))
                {
                        return "error_empty_value";
                }
                return null;
        }

        public String validateAge(int age)
        {
                System.out.println("age is ..." + age);

                if (age < 0)
                {
                        return "error_negative_age";
                }
                else if (age > 110)
                {
                        return "error_too_large_age";
                }

                return null;
        }

        public String validateEmail(String email)
        {
                System.out.println("email is ..." + email);
                if (email == null || email.equalsIgnoreCase(""))
                {
                        return "error_empty_value";
                }

                Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
                Matcher m = p.matcher(email);

                // check whether any match is found
                boolean matchFound = m.matches();

                if (!matchFound)
                {
                        return "error_invalid_email";
                }

                return null;
        }
}

The above Java class validates the given input field value from JSP and returns the error code to be displayed.

Here is the spring configuration file for the DWR setup.

Configuration File

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-2.0.xsd">
<dwr:controller id="dwrController" debug="true" />
<bean id="dwrHandlerMappings" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="1" />
<property name="alwaysUseFullPath" value="true"></property>
<property name="mappings">
<props>
<prop key="/dwr/**/*">dwrController</prop>
<prop key="/demo.htm">techdive_controller</prop>
</props>
</property>
</bean>
<bean id="validateService" class="in.techdive.spring.dwr.ValidateService">
<dwr:remote javascript="validateService">
<dwr:include method="validateName"/>
<dwr:include method="validateAge"/>
<dwr:include method="validateEmail"/>
</dwr:remote>
</bean>
<!-- messageSource used to load Bundle Properties in order to display Validation Error Messages -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
</bean>
<!-- Main Controller Class definition -->
<bean name="techdive_controller" class="in.techdive.spring.dwr.Techdive_Controller">
<property name="sessionForm" value="true"/>
<property name="commandName" value="cmdData"/>
<property name="commandClass" value="in.techdive.spring.dwr.Entity"/>
<property name="formView" value="ValidatePage"/>
<property name="successView" value="ValidatePage"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

Here is the Techdive_Controller class, which is a Simple Form Controller class used to display the JSP page.

Techdive_Controller Class

package in.techdive.spring.dwr;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class Techdive_Controller extends SimpleFormController
{

        protected Map referenceData(HttpServletRequest request, Object command,
                        Errors errors) throws Exception
        {
                return new HashMap();
        }

        public ModelAndView onSubmit(Object command) throws ServletException
        {
                String name = ((Entity) command).getName();

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("name", name);
                map.put("age", ((Entity) command).getAge());
                map.put("email", ((Entity) command).getEmail());

                return new ModelAndView("OutputPage", "model", map);
        }
}

For this example the onSubmit(..) method is a sample one which just displays the input in next page Outputpage.jsp

Outputpage.jsp

<%@ page contentType="text/html;charset=UTF-8" %>  
<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>

<head>
        <title> Validation Demo - TechDive.in</title>
</head>

<body>

<h1>Validation Demo - TechDive.in - Response Form</h1>

        <p>Name from Server = <c:out value="${model.name}" /></p>
       
        <p>Age from Server = <c:out value="${model.age}" /></p>
       
        <p>Email from Server = <c:out value="${model.email}" /></p>
       
       
</body>

</html>

Here is the messages.properties file which is used to display error messages in JSP file for validation

messages.properties

error_empty_value=Error: Empty Value
error_negative_age=Error: Age should not be Negative
error_too_large_age=Error: Age should be less than 110
error_invalid_email=Error: Email is invalid

Take a look at the web.xml file as follows

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" >
<servlet>
<servlet-name>springdwr</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springdwr</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>
index.jsp
</welcome-file>
</welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>/spring</taglib-uri>
<taglib-location>/WEB-INF/tld/spring-form.tld</taglib-location>
</taglib>
</jsp-config>
<servlet>
<servlet-name>dwr</servlet-name>
<servlet-class>org.directwebremoting.spring.DwrSpringServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springdwr</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</web-app>

In this way, DWR can be used for validation in Spring applications.

Technology: 

Search