Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

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.








dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

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



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
 */
@Controller
public class myController {
     
    @Autowired
    StudentService service;

    @RequestMapping("/studentData")
    public String gotoViewPage() {
        return "courseAndStudent";
    }

    @ModelAttribute("courseMap")
    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"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Courses And Students</title>
           
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
    $(document).ready(function () {

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

                function (data) {

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

                    });
                    table += '</table>';
                    $("#studentTable").html(table);

                });
            }
        });
    });
</script>   
            
 </head>
 
 <body>
          <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>  
                </c:forEach>
 
          </select>
        
     <div id="studentTable">
         
     </div>     

  </body>
</html>


Pojo model class
package models;

public class Student {

    String name;
    String id;
    String year;

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

 //getter setters
}