Spring 3 MVC with jQuery post method

Spring 3 MVC with jQuery post method


Posted in : Spring Posted on : April 25, 2011 at 5:41 PM Comments : [ 0 ]

In this tutorial, you will learn how to integrate jQuery with Spring 3 MVC to post data to server and get back response.

Spring 3 MVC with jQuery post method

In this tutorial, you will learn how to integrate jQuery with Spring 3 MVC to post data to server and get back response.

In the given below example, we will send data to server using jQuery's post() method. We will also use JSON Jackson library to convert the response to an appropriate client supported data. It is done by Spring using JSON Jackson library. The  returned data of the method annotated with  @ResponseBody will converted by the Spring  automatically to client supported appropriate data.

You can download  JSON Jackson library  from here.

Application Flow

When you first execute the application, it will show you :

When you enter number and hit Add button :

When you hit OK, it will show you the Sum :

At Console, you can see the following message printed by log4j Logger class :

The jar File used :

Project Hierarchy :

CODE

web.xml (/Spring3MvcJquery/WebContent/WEB-INF/web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/dev/*</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<welcome-file-list>
<welcome-file>/WEB-INF/jsp/ajax-add-page.jsp</welcome-file>
</welcome-file-list>
</web-app>

spring-servlet.xml (/Spring3MvcJquery/WebContent/WEB-INF/spring-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"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- Declare a view resolver -->
<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/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>

applicationContext.xml (/Spring3MvcJquery/WebContent/WEB-INF/applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc 
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<!-- Activates various annotations to be detected in bean classes -->
<context:annotation-config />

<!--
Scans the classpath for annotated components that will be
auto-registered as Spring beans. For example @Controller and @Service.
Make sure to set the correct base-package
-->
<context:component-scan base-package="com.devmanuals.tutorial" />

<!--
Configures the annotation-driven Spring MVC Controller programming
model. Note that, with Spring 3.0, this tag works in Servlet MVC only!
-->
<mvc:annotation-driven />

</beans>

AjaxController.java (/Spring3MvcJquery/src/com/devmanuals/tutorial/controller/AjaxController.java)

package com.devmanuals.tutorial.controller;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.devmanuals.tutorial.service.ArithmeticService;

/**
* Handles and retrieves the main requests
*/
@Controller
@RequestMapping("/main/ajax")
public class AjaxController {

protected static Logger logger = Logger.getLogger("controller");

@Resource(name = "springService")
private ArithmeticService springService;

/**
* Handles and retrieves the AJAX Add page
*/
@RequestMapping(value = "/add", method = RequestMethod.GET)
public String getAjaxAddPage() {
logger.debug("Received request to show AJAX, add page");

// It resolves the /WEB-INF/jsp/ajax-add-page.jsp
return "ajax-add-page";
}

/**
* Handles request for adding two numbers
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody
Integer add(
@RequestParam(value = "inputNumber1", required = true) Integer inputNumber1,
@RequestParam(value = "inputNumber2", required = true) Integer inputNumber2,
Model model) {
logger.debug("Received request to add two numbers");

Integer sum = springService.add(inputNumber1, inputNumber2);
return sum;
}
}

ArithmeticService.java (/Spring3MvcJquery/src/com/devmanuals/tutorial/service/ArithmeticService.java)

package com.devmanuals.tutorial.service;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @Service enables the class to be used as a Spring service
* @Transactional enables transaction support for this class
*/
@Service("springService")
@Transactional
public class ArithmeticService {

protected static Logger logger = Logger.getLogger("service");

/**
* Adds two numbers
*/
public Integer add(Integer operand1, Integer operand2) {
logger.debug("Adding two numbers");
return operand1 + operand2;
}

}

log4j.properties (/Spring3MvcJquery/src/log4j.properties)

log4j.rootLogger=ERROR,console

#Console Appender 
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%5p] [%t %d{hh:mm:ss}] (%F:%M:%L) %m%n

#Custom assignments
log4j.logger.controller=DEBUG,console
log4j.logger.service=DEBUG,console
log4j.logger.dao=DEBUG,console

#Disable additivity
log4j.additivity.controller=false
log4j.additivity.service=false
log4j.additivity.dao=false

ajax-add-page.jsp (/Spring3MvcJquery/WebContent/WEB-INF/jsp/ajax-add-page.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">

<script type="text/javascript"
src="/Spring3MvcJquery/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
var jq = jQuery.noConflict();
</script>

<title>jQuery with Spring3MVC</title>

</head>
<body bgcolor="#306EFF">
<font color="white">

<h3>jQuery with Spring3MVC</h3>
<h4>Adding number using jQuery Ajax</h4>
<div style="border: 3px solid #FFFFFF; width: 250px;"><b><i>Enter
Two Numbers for Addition:</i></b><br />
<input id="inputNumber1" type="text" size="5"> + <input
id="inputNumber2" type="text" size="5"> <input type="submit"
value="Add" onclick=
add();
/> <br />
Sum: <span id="sum">(Sum will be output here)</span></div>


<script type="text/javascript">
function add() {
jq(function() {
jq.post("/Spring3MvcJquery/dev/main/ajax/add", {
inputNumber1 : jq("#inputNumber1").val(),
inputNumber2 : jq("#inputNumber2").val()
}, function(data) {
alert("Added Number below the button");
jq("#sum").replaceWith('__tag_39$31_' + data + '__tag_39$57_');
});
});
}
</script> </font>
</body>
</html>

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics