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 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.
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
Here is the Techdive_Controller class, which is a Simple Form Controller class used to display the JSP page.
Techdive_Controller Class
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 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_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
In this way, DWR can be used for validation in Spring applications.