Interview Questions

Spring DWR Integration

In this section, let us discuss about DWR integration with Spring.

DWR (DIRECT WEB REMOTING) is a framework to use Ajax in Java web application.

Lets consider an example of populating child drop down list from parent using DWR in Spring application. Consider the following register.jsp file

register.jsp

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>    
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>User Registration</title>
    </head>

<body>
   
<form:form method="POST" commandName="user" name="registerForm">
    <table>
        <tr>
                <td>First Name :</td>
                <td><form:input path="firstName" ></form:input></td>
        </tr>
        <tr>
                <td>Last Name :</td>
                <td><form:input path="lastName" ></form:input></td>
        </tr>
        <tr>
                <td>User Name :</td>
                <td><form:input path="userName" ></form:input></td>
        </tr>
        <tr>
                <td>Password :</td>
                <td><form:password path="passWord" /></td>
        </tr>
        <tr>
                <td>Country :</td>
                <td>
                        <form:select path="country" onchange="populateItems()">
                                <form:option value="0" >Select </form:option>
                                <form:options items="${listCountries}" />
                        </form:select>
                </td>
        </tr>
               
        <tr>
                <td>State :</td>
                <td><form:select path="state">
                        <form:option value="0" >Select </form:option>
                        <form:options items="${listStates}" />
                </form:select></td>
        </tr>
               
        <tr>
                <td>email :</td>
                <td><form:input path="email" /></td>
        </tr>
               
        <tr>
                <td colspan="2"><input type="submit"></td>
        </tr>
    </table>
</form:form>

</body>
</html>

It contains fields for displaying user information like userName, password, country, state etc.

The spring controller class RegistrationController is as follows.

RegistrationController Class

package in.techdive.java.ajax;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import in.techdive.java.ajax.User;

public class RegistrationController extends SimpleFormController
{
       
        private ModelMap modelMap = new ModelMap();

        public RegistrationController()
        {
                setCommandClass(User.class);
                setCommandName("user");
        }
       
        protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
        {
                User user  = (User)command;
                ModelAndView mv = new ModelAndView("/register","user",user);
                return mv;
        }
       
        protected Map referenceData(HttpServletRequest request) throws Exception
        {
                List<String> countries = new ArrayList<String>();
                countries.add("INDIA");
                countries.add("US");
                countries.add("AUSTRALIA");
                HttpSession session = request.getSession();
                session.setAttribute("listCountries", countries);
        return modelMap;
        }

}

User Bean Class

package in.techdive.java.ajax;

public class User implements Serializable {

        private static final long serialVersionUID = 831352418170872041L;

        public User() {
        }
       
        private long userId;
        private String userName;
        private String passWord;
        private String email;
        private String firstName;
        private String lastName;
        private String country;
        private String state;

        public long getUserId() {
                return userId;
        }
        public void setUserId(long userId) {
                this.userId = userId;
        }
        public String getUserName() {
                return userName;
        }
        public void setUserName(String userName) {
                this.userName = userName;
        }
        public String getEmail() {
                return email;
        }
        public void setEmail(String email) {
                this.email = email;
        }
        public String getPassWord() {
                return passWord;
        }
        public void setPassWord(String passWord) {
                this.passWord = passWord;
        }
       
        public String getCountry()
        {
                return country;
        }
       
        public void setCountry(String country)
        {
                this.country = country;
        }

        public String getFirstName() {
                return firstName;
        }

        public void setFirstName(String firstName) {
                this.firstName = firstName;
        }

        public String getLastName() {
                return lastName;
        }

        public void setLastName(String lastName) {
                this.lastName = lastName;
        }

        public String getState() {
                return state;
        }

        public void setState(String state) {
                this.state = state;
        }
}

In the UI JSP page, lets use DWR to fill state drop-down list, based on the country selected in the Country drop down list.

The beans to be added for DWR in Spring configuration file are as follows

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:util="http://www.springframework.org/schema/util"
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.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-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>
</props>
</property>
</bean>
<bean id="itemsUtilService" class="in.techdive.java.ajax.ItemsUtilService">
<dwr:remote javascript="itemsUtilService">
<dwr:include method="getItemsUtilService"/>
</dwr:remote>
</bean>
<bean id="defaultViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="requestContextAttribute" value="rc" />
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!-- URL and Corresponding Controller mapping to come here -->
<property name="urlMap">
<map>
<entry key="/" value-ref = "RegistrationController"/>
<entry key="/register.htm" value-ref = "RegistrationController"/>
</map>
</property>
</bean>
<bean id="RegistrationController" class="in.techdive.java.ajax.RegistrationController">
<property name="formView" value="register" />
<property name="successView" value="welcome" />
</bean>
</beans>

Now lets create ItemsUtilService.java class whose method will be called from java script. The method getItemsUtilService(String country) takes the string country as input and returns the list of states for the country.

ItemsUtilService Class

package in.techdive.java.ajax;

public class ItemsUtilService {
       
        private List<String> listIndiaStates = new ArrayList<String>();
       
        private List<String> listUSStates = new ArrayList<String>();
       
        private List<String> listAUSStates = new ArrayList<String>();
       
        private Map<String,List<String>> stateCountryMap = new HashMap<String,List<String>>();

        public ItemsUtilService() {
                super();
               
                listIndiaStates.add("Andhra Pradesh");
                listIndiaStates.add("Bihar");
                listIndiaStates.add("Maharashtra");
                listIndiaStates.add("Karnataka");
                listIndiaStates.add("Tamil Nadu");
                listIndiaStates.add("West Bengal");
               
                listUSStates.add("Arizona");
                listUSStates.add("California");
                listUSStates.add("Massachusetts");
                listUSStates.add("New Jersey");
                listUSStates.add("New York");
                listUSStates.add("Washington");
               
                listAUSStates.add("New South Wales");
                listAUSStates.add("QueensLand");
                listAUSStates.add("Victoria");
                listAUSStates.add("Northern Territory");
               
               
                stateCountryMap.put("INDIA", listIndiaStates);
                stateCountryMap.put("US", listUSStates);
                stateCountryMap.put("AUSTRALIA", listAUSStates);
        }
       
        public List<String> getItemsUtilService(String country)
        {
                List<String> listStates = new ArrayList<String>();
                System.out.println(country);
                if(country!=null)
                {                      
                                listStates = stateCountryMap.get(country);
                                                               
                }
                return listStates;
        }
}

Now, take a look at the complete JSP file and how the JavaScript calls are made using DWR methods from JSP file.

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

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Registration</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/itemsUtilService.js'/>"></script>

<script type="text/javascript">
function populateItems()
{
        var ct = document.getElementById('country').value;
        alert("ct...."+ct);
        itemsUtilService.getItemsUtilService(ct,postCommentHandler);
}

// AJAX Callback Function
function postCommentHandler(attrs)
{
        if(attrs == null)
        {
        }
        else
        {
            var st = document.getElementById('state');
            st.options.length = 0;
            st.add(new Option('Select', '0'));
       
            for (var i = 0; i < attrs.length; i++)
            {
                st.add(new Option(attrs[i], attrs[i]));
            }
        }
}
</script>
<body>
   
<form:form method="POST" commandName="user" name="registerForm">
        <table>
                <tr>
                        <td>First Name :</td>
                        <td><form:input path="firstName" ></form:input></td>
                </tr>
                <tr>
                        <td>Last Name :</td>
                        <td><form:input path="lastName" ></form:input></td>
                </tr>
                <tr>
                        <td>User Name :</td>
                        <td><form:input path="userName" ></form:input></td>
                </tr>
                <tr>
                        <td>Password :</td>
                        <td><form:password path="passWord" /></td>
                </tr>
               
                <tr>
                        <td>Country :</td>
                        <td><form:select path="country" onchange="populateItems()">
                        <form:option value="0" >Select </form:option>
                                        <form:options items="${listCountries}" />
                        </form:select></td>
                </tr>
               
                <tr>
                        <td>State :</td>
                        <td><form:select path="state">
                                <form:option value="0" >Select </form:option>
                                <form:options items="${listStates}" />
                        </form:select></td>
                </tr>
               
                <tr>
                        <td>email :</td>
                        <td><form:input path="email" /></td>
                </tr>
               
                <tr>
                        <td colspan="2"><input type="submit"></td>
                </tr>
        </table>
</form:form>
</body>
</html>

The ".js" files like engine.js, util.js and interface/itemsUtilService.js are to be included in the JSP file. The method mapping from itemsUtilService to the POJO class ItemsUtilService.java using the bean configuration in spring.

Finally one more change has to be made in web.xml as follows

web.xml changes

<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>

In this way DWR framework can be integrated with spring.

Note: dwr.jar should be added to the lib folder.

For Further Study
Spring DWR Validation