Ajax request processing using Spring MVC 3.X

Are you trying to integrate DWR and Spring MVC 3.X? If your answer is yes, then you’re wasting valuable development time in fixing integration problems.
May be it is good to have DWR library for Ajax calls while developing a web application, but when you are using Spring MVC3 for developing your application this is not a good solution, because Spring Frame work itself capable for handling Ajax Calls. In this article, I would like to explain

Basic way of handling Ajax calls using Spring MVC (Spring Rest capabilities):

  1. Dependency configuration:
    <dependency>
    
    <groupId>org.springframework</groupId>
    
    <artifactId>spring-beans</artifactId>
    
    <version>3.1.3.RELEASE</version>
    
    </dependency>
    
    <dependency>
    
    <groupId>org.springframework</groupId>
    
    <artifactId>spring-context</artifactId>
    
    <version>3.1.3.RELEASE</version>
    
    </dependency>
    
    <dependency>
    
    <groupId>org.springframework</groupId>
    
    <artifactId>spring-web</artifactId>
    
    <version>3.1.3.RELEASE</version>
    
    </dependency>
    
    <dependency>
    
    <groupId>org.springframework</groupId>
    
    <artifactId>spring-webmvc</artifactId>
    
    <version>3.1.3.RELEASE</version>
    
    </dependency>
    
    <dependency>
    
    <groupId>org.springframework</groupId>
    
    <artifactId>spring-core</artifactId>
    
    <version>3.1.3.RELEASE</version>
    
    </dependency>
    
     
  2. Server Side Coding: The code below describes how to write a Controller to process asynchronous requests.
    @Controller
    @RequestMapping(value="/ajax")
    public class  AjaxController {
    @RequestMapping(value = "/searchEmployee", method = RequestMethod.GET)
    public @ResponseBody final List<SuggestionData> searchEmployee (@RequestParam final String searchString) {
    List suggestionTexts = null;
    if (hasText(searchString)) {
    //TODO code to search employees in the database. sees the below searchEmployee(String searchString) method
    }
    return suggestionTexts;
    } 

    Here @RequestParam is an annotation which will bind request parameter to a variable in method scope. For example searchString.

    @ResponseBody annotation tells spring that we want to send the returned object as a resource to the client, converted into some representational form that the client can accept. For example normal String (text/plain) or in JSON format (application/json).

    Spring has provided some HTTP message converters to convert resources to and from various Java Types. For example converting List<SuggestionData> to JSON format

    @RequestMapping annotation specifies that the following class or method should handle the requests whose path is having the value mentioned as a value and method attribute specifies the type of HTTP method (Get or POST).

    In the above code snippet we can see this annotation specified in two places, one is above the class and other is above the method.

    At class level means: The following class is specifically designed to handle all the requests whose request path starts with “/ajax”.

    At method level means:  The following method has been designed to handle specific request whose path is “/searchEmployee

    As it was specified in class and method level, if you want to request searchEmployee your URL path should be like this

       /ajax/ searchEmployee

  3. Client side Coding: To request asynchronously from client side we can use JQuery or Dojo or simple JavaScript. In this article I am using JQuery.
    $(document).ready(function() {
    $("#employeeSearch").autocomplete({
    source : function(request, response) {
    $.getJSON("ajax/searchEmployee",{searchString: request.term },function(dataFromServer) {
                           if(dataFromServer != null && dataFromServer.length > 0) {
                                 response (dataFromServer);
                          } else {
                                   //reset user Information
                          }
                      }).error (function(xhr, desc, err) {
                            // handle Error
                      });
                  },
                 select : function(event, ui) {
                       //ui.item.hiddenValue
                      $("#employeeName").val(ui.item.value);// call will come here when you select the suggested text after search
                 }
    });
    
  4. Other code snippets used internally.
  /*
  * used as a data object for auto-complete functionality
 */
   public class SuggestionData implements Serializable {

private static final long serialVersionUID = 1L;

private String lable;
private String value;
private String hiddenValue;
    //setters and getter
   }

  @Override
public List<SuggestionData> searchEmployee(String searchString) {
List<SuggestionData> matchingEmployees = new ArrayList<SuggestionData>();
List<Employee> employees = this.employeeRepository.findByNameLike("%" + searchString + "%");
for (Iterator<Employee> iterator = employees.iterator(); iterator.hasNext();) {
SuggestionData suggestionText     = new SuggestionData();
Employee employeeNew             = iterator.next();
String employee                 = employeeNew.getName();
suggestionText.setLable(employee);
suggestionText.setValue(employee);
suggestionText.setHiddenValue(String.valueOf(employeeNew.getEmployeeId()));
matchingEmployees.add(suggestionText);
}
return matchingEmployees;
}

This is the code to search for an employee when user start key in some characters’ in the input field or you can simply say suggestion text or auto complete behavior.
Like this you can develop code using Spring MVC controller to process ajax requests(Spring Rest capabilities).

Summary
Article Name
Ajax request processing using Spring MVC 3
Author
Description
Senior Software Engineer

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

About Mohan Srihari Kantipudi

2 comments

  1. This Post is basically for who still struggling and wasting time in
    fixing integration problems with Spring MVC and DWR.

  2. Good stuff

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current month ye@r day *

Scroll To Top
Email
Print