Saturday, February 2, 2013

Ajax with Spring 3

Generating Table using ajax request and json with spring 3 annotated controller

Yesterday i had a task where i had to build a jsp page with spring 3 where, changing a dropdown value would result in a dynamic table related to that value. It was fun. Here i wont go into the details of my work. I will simply log how to handle a $.getJson method with Spring annotated controller. Wont go into details. i guess the screen shot and code will be enough.

When you select a course, the corresponding students table will be generated using an ajax request to get the data and then a little bit of jQuery to print the table.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <context:component-scan base-package="controllers" />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
        <property name="suffix">
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="order" value="1" />
        <property name="messageConverters">
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

Spring 3 Annotated Controller

 * To change this template, choose Tools | Templates
 * and open the template in the editor.
package controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import models.*;
import org.springframework.web.bind.annotation.RequestParam;

 * @author nayef
public class myController {
    StudentService service;

    public String gotoViewPage() {
        return "courseAndStudent";

    public Map<String, String> getCourseMap() {
        Map<String, String> courseMap = new HashMap<String, String>();
        courseMap.put("cse110", "Basic Java");
        courseMap.put("cse111", "Advanced Java");
        courseMap.put("cse220", "Data Structure");
        courseMap.put("cse221", "Algorithms");

        return courseMap;

    @RequestMapping(value = "/studentList")
    public @ResponseBody
    List<Student> getStudentsForCourse(@RequestParam("courseId") String courseId) {

        List<Student> studentList = service.getStudentsForCourse(courseId);
        return studentList;

JSP for view

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<%@ taglib uri="" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Courses And Students</title>
<script src="//">
    $(document).ready(function () {

        $("#course").change(function () {
            var courseIdStr = $("#course").val();
            if (courseIdStr == '0') {
            } else {
                $.getJSON("<c:url value='/studentList'/>", {
                    courseId: courseIdStr

                function (data) {

                    var table = '<table>';
                    $.each(data, function (index, student) {
                        table += '<tr><td>' + + '</td><td>' + + '</td><td>' + student.year + '</td></tr>';

                    table += '</table>';

          <select id="course" name="course" class="course">     

              <option value="0">Select Course</option>
                <c:forEach items="${courseMap}" var="course" >  
                        <option value="${course.key}">${course.value}</option>  
     <div id="studentTable">


Pojo model class
package models;

public class Student {

    String name;
    String id;
    String year;

    public Student(String name, String id, String year) { = name; = id;
        this.year = year;

 //getter setters