Now what if I want to change my dashboard according to new values selected in dropdowns in dashboard? Well, to do just just that you can pass your single value or object value to the class using AJAX and JSON and then retrieve the new dashboard values based on selected options. In this example I will show you how to pass JSON Arrays and then parse it in spring controller class to retrieve each value individually.
Project Structure:
web.xml
-----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
sdnext-servlet.xml
--------------------------------------------------
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">
<context:component-scan base-package="com.login" />
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/img" />
<mvc:resources mapping="/js/**" location="/js" />
<mvc:resources mapping="/css/**" location="/css" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="true"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
</beans>
Index.jsp
----------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ 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>Insert title here</title>
</head>
<body>
<form:form method="POST" action="ajaxPage.html">
<table>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
ajax.js
-------------------------------------------------
var k = 0;
$(document).ready(function(){
callAjax();
$('#submit').click(function(event) {
$("#re").empty();
var arr = {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
$.ajax({
type: 'POST',
// dataType: 'json',
contentType:'application/json',
url: "ajax.html",
data: JSON.stringify(arr),
success: function(response) {
alert("success");
var jsonType = JSON.parse(response);
alert("jsonType "+ jsonType);
$.each(jsonType, function(key,value){
alert("key "+key);
for(var i = 0; i < value.length; i++)
{
$("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
}
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed'+errorThrown);
}
});
});
});
function callAjax() {
$("#re").empty();
var arr = {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
$.ajax({
type: 'POST',
// dataType: 'json',
contentType:'application/json',
url: "ajax.html",
data: JSON.stringify(arr),
success: function(response) {
alert("success");
var jsonType = JSON.parse(response);
alert("jsonType "+ jsonType);
$.each(jsonType, function(key,value){
alert("key "+key);
for(var i = 0; i < value.length; i++)
{
$("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
}
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed'+errorThrown);
}
});
}
LoginController.java
----------------------------------------------------
package com.login.controller;
import java.io.IOException;
import java.util.ArrayList;
import javassist.bytecode.Descriptor.Iterator;
import org.apache.catalina.User;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import antlr.collections.List;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.login.bean.testArrayListInAjax;
@Controller
public class LoginController {
testArrayListInAjax obj1 = null;
@RequestMapping(value = "/ajaxPage")
public ModelAndView forwordLogin() {
return new ModelAndView("ajax");
}
@RequestMapping(value = "/ajax")
public @ResponseBody
String ShowUserDetails(@RequestBody String arr1) {
Gson gson = new Gson();
/*Note: Now i slice out the String arr1 to the format needed to convert String to JSONArray.*/
int first = arr1.indexOf("[");
int last = arr1.lastIndexOf("]")+1;
String l = arr1.substring(first, last);
ArrayList FirstNames = new ArrayList();
ArrayList LastNames = new ArrayList();
try {
JSONArray jsonarray = new JSONArray(l);
System.out.println("jsonarr "+jsonarray);
for(int i=0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String firstName = jsonobject.getString("firstName");
String lastName = jsonobject.getString("lastName");
FirstNames.add(firstName);
LastNames.add(lastName);
//Do whatever manipulation now you want to do with each individual value.
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("catch");
e.printStackTrace();
}
obj1 = new testArrayListInAjax();
obj1.setAr1(FirstNames);
return gson.toJson(obj1);
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
}
testArrayListInAjax
-----------------------------------------
package com.login.bean;
import java.util.ArrayList;
public class testArrayListInAjax
{
ArrayList ar1 = new ArrayList();
public ArrayList<String> getAr1()
{
return ar1;
}
public void setAr1()
{
ar1.add("ArrayValue1");
ar1.add("ArrayValue2");
}
public void setAr1(ArrayList a)
{
ar1.add(a.get(0));
ar1.add(a.get(1));
}
}
ajax.jsp
----------------------------------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/ajax.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<select id="param1">
<option value="Khushboo">Khushboo</option>
<option value="Singh">Khushi</option>
</select>
</td>
<td colspan="2">
<select id="param2">
<option value="singh">Singh</option>
<option value="Singh">Singh</option>
</select>
</td>
<td colspan="2">
<button type="button" id = "submit">submit</button>
</td>
</tr>
</table>
<table id="re" name="re" border="2" cellspacing="4" cellpadding="4">
</table>
</body>
</html>
Index screen
------------------------------
Now in my scenario I have explained how to pass a JSON array and then individually retrieve the values but i have not really changed the values based on parameters. But you can do that using this very code but instead of passing a static array you can pass the parameters individually. Using this code you can dynmaically change table values using AJAX and JSON. This is just the brief cut out on what i will be implementing in my dashboard in order to make it even more intuitive.
Project Structure:
web.xml
-----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>sdnext</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/sdnext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sdnext</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
sdnext-servlet.xml
--------------------------------------------------
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
">
<context:component-scan base-package="com.login" />
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/img" />
<mvc:resources mapping="/js/**" location="/js" />
<mvc:resources mapping="/css/**" location="/css" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="true"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer"/>
</property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
</beans>
Index.jsp
----------------------------------------------
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ 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>Insert title here</title>
</head>
<body>
<form:form method="POST" action="ajaxPage.html">
<table>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
ajax.js
-------------------------------------------------
var k = 0;
$(document).ready(function(){
callAjax();
$('#submit').click(function(event) {
$("#re").empty();
var arr = {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
$.ajax({
type: 'POST',
// dataType: 'json',
contentType:'application/json',
url: "ajax.html",
data: JSON.stringify(arr),
success: function(response) {
alert("success");
var jsonType = JSON.parse(response);
alert("jsonType "+ jsonType);
$.each(jsonType, function(key,value){
alert("key "+key);
for(var i = 0; i < value.length; i++)
{
$("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
}
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed'+errorThrown);
}
});
});
});
function callAjax() {
$("#re").empty();
var arr = {"ar1": [
{
"firstName": "Khushboo",
"lastName": "Singh"
},
{
"firstName": "Khushi",
"lastName": "Singh"
}
]
};
$.ajax({
type: 'POST',
// dataType: 'json',
contentType:'application/json',
url: "ajax.html",
data: JSON.stringify(arr),
success: function(response) {
alert("success");
var jsonType = JSON.parse(response);
alert("jsonType "+ jsonType);
$.each(jsonType, function(key,value){
alert("key "+key);
for(var i = 0; i < value.length; i++)
{
$("#re").append("<tr><th>"+key.toUpperCase()+"</th><td>"+value[i]+"</td></tr>");
}
});
},
error: function(xhr, textStatus, errorThrown){
alert('request failed'+errorThrown);
}
});
}
LoginController.java
----------------------------------------------------
package com.login.controller;
import java.io.IOException;
import java.util.ArrayList;
import javassist.bytecode.Descriptor.Iterator;
import org.apache.catalina.User;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import antlr.collections.List;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.login.bean.testArrayListInAjax;
@Controller
public class LoginController {
testArrayListInAjax obj1 = null;
@RequestMapping(value = "/ajaxPage")
public ModelAndView forwordLogin() {
return new ModelAndView("ajax");
}
@RequestMapping(value = "/ajax")
public @ResponseBody
String ShowUserDetails(@RequestBody String arr1) {
Gson gson = new Gson();
/*Note: Now i slice out the String arr1 to the format needed to convert String to JSONArray.*/
int first = arr1.indexOf("[");
int last = arr1.lastIndexOf("]")+1;
String l = arr1.substring(first, last);
ArrayList FirstNames = new ArrayList();
ArrayList LastNames = new ArrayList();
try {
JSONArray jsonarray = new JSONArray(l);
System.out.println("jsonarr "+jsonarray);
for(int i=0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String firstName = jsonobject.getString("firstName");
String lastName = jsonobject.getString("lastName");
FirstNames.add(firstName);
LastNames.add(lastName);
//Do whatever manipulation now you want to do with each individual value.
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("catch");
e.printStackTrace();
}
obj1 = new testArrayListInAjax();
obj1.setAr1(FirstNames);
return gson.toJson(obj1);
}
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView welcome() {
return new ModelAndView("index");
}
}
testArrayListInAjax
-----------------------------------------
package com.login.bean;
import java.util.ArrayList;
public class testArrayListInAjax
{
ArrayList ar1 = new ArrayList();
public ArrayList<String> getAr1()
{
return ar1;
}
public void setAr1()
{
ar1.add("ArrayValue1");
ar1.add("ArrayValue2");
}
public void setAr1(ArrayList a)
{
ar1.add(a.get(0));
ar1.add(a.get(1));
}
}
ajax.jsp
----------------------------------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/ajax.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<select id="param1">
<option value="Khushboo">Khushboo</option>
<option value="Singh">Khushi</option>
</select>
</td>
<td colspan="2">
<select id="param2">
<option value="singh">Singh</option>
<option value="Singh">Singh</option>
</select>
</td>
<td colspan="2">
<button type="button" id = "submit">submit</button>
</td>
</tr>
</table>
<table id="re" name="re" border="2" cellspacing="4" cellpadding="4">
</table>
</body>
</html>
Index screen
------------------------------
Now in my scenario I have explained how to pass a JSON array and then individually retrieve the values but i have not really changed the values based on parameters. But you can do that using this very code but instead of passing a static array you can pass the parameters individually. Using this code you can dynmaically change table values using AJAX and JSON. This is just the brief cut out on what i will be implementing in my dashboard in order to make it even more intuitive.