Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Thursday, January 13, 2011

Spring MVC 3 and jQuery Integration Tutorial

In this tutorial we will build a simple Spring MVC 3 application with AJAX capabilities using jQuery. We will explore how to post data using jQuery.post() and process the result. We will be developing a non-AJAX application first then convert it to an AJAX-powered version later.

What is jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Source: http://jquery.com/

What is AJAX?
Ajax is a group of interrelated web development methods used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not needed, and the requests need not be asynchronous.

Like DHTML and LAMP, Ajax is not one technology, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

Source: http://en.wikipedia.org/wiki/Ajax_(programming)

Our application is a simple arithmetic operation that adds two numbers and displays the sum. Here's a screenshot of the non-AJAX version:


Here's a screenshot of the AJAX version:


Notice nothing much is different, except that the non-AJAX version will display the result on another page, while the AJAX version will display on the same page. Actually, this is the main difference! With AJAX we have a responsive, desktop-like application. No page refresh.

Non-AJAX Version

Let's develop first our non-AJAX Spring MVC application.

We need a controller to handle the user's requests. Let's call it NonAjaxController

NonAjaxController
package org.krams.tutorial.controller;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.krams.tutorial.service.ArithmeticService;
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;

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

 protected static Logger logger = Logger.getLogger("controller");
 
 @Resource(name="springService")
 private ArithmeticService springService;
 
    /**
     * Handles and retrieves the non-AJAX, ordinary Add page
     */
    @RequestMapping(value="/add", method = RequestMethod.GET)
    public String getNonAjaxAddPage() {
     logger.debug("Received request to show non-AJAX, ordinary add page");
    
     // This will resolve to /WEB-INF/jsp/nonajax-add-page.jsp
     return "nonajax-add-page";
 }
    
    /**
     * Handles request for adding two numbers
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String 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");
  
  // Delegate to service to do the actual adding
  Integer sum = springService.add(inputNumber1, inputNumber2);
  
  // Add to model
  model.addAttribute("sum", sum);
  
     // This will resolve to /WEB-INF/jsp/nonajax-add-result-page.jsp
  return "nonajax-add-result-page";
 }
    
}
This controller declares the following mappings:
/main/nonajax/add (GET) - retrieves the add page
/main/nonajax/add POST) - computes the sum and retrieves the result page
The first mapping receives a request to display the add page. The second mapping receives two numbers and delegates the computation to the ArithmeticService. When the ArithmeticService is done processing, the controller then forwards the result to another JSP page which displays the result.

Here are the JSP pages:

nonajax-add-page.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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">
 
 <title>Spring MVC - jQuery Integration Tutorial</title>
</head>
<body>

<h3>Spring MVC - jQuery Integration Tutorial</h3>
<h4>Non-AJAX version</h4>

<c:url var="addUrl" value="/krams/main/nonajax/add" />
<form method="POST" action="${addUrl}">

Demo 1 
<div style="border: 1px solid #ccc; width: 250px;">
 Add Two Numbers: <br/>
 <input id="inputNumber1" name="inputNumber1" type="text" size="5"> +
 <input id="inputNumber2" name="inputNumber2" type="text" size="5">
 <input type="submit" value="Add" /> <br/>
 Sum: (Result will be shown on another page)
</div>

</form>

</body>
</html>

nonajax-add-result-page.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ 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">
 
 <title>Spring MVC - jQuery Integration Tutorial</title>
</head>
<body>

<h3>Spring MVC - jQuery Integration Tutorial</h3>
<h4>Non-AJAX version</h4>

Demo 1 Result
<div style="border: 1px solid #ccc; width: 250px;">
 Sum: ${sum}
</div>

</body>
</html>

Let's run the application. We'll be adding two numbers: 5 and 10, and we expect 10 as the result.

To access the Add page, enter the following URL in your browser:
http://localhost:8080/spring-mvc-jquery/krams/main/nonajax/add


Here's the result:

Now let's examine the service that performs the actual processing:

ArithmeticService
package org.krams.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");
  // A simple arithmetic addition
  return operand1 + operand2;
 }
 
}
This is a very simple POJO service that contains a simple arithmetic function. To make this POJO available as a Spring service bean, we just add the @Service annotation.

AJAX Version

Let us now convert our non-AJAX application to an AJAX-powered version.

To create our AJAX application we will create one JSP page to handle both the request and result on the same page. This is the primary benefit of AJAX. We also need another controller to handle the page request.

Here is the controller.

AjaxController
package org.krams.tutorial.controller;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.krams.tutorial.service.ArithmeticService;
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;

/**
 * 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");
     
     // This will resolve to /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");
  
  // Delegate to service to do the actual adding
  Integer sum = springService.add(inputNumber1, inputNumber2);
  
  // @ResponseBody will automatically convert the returned value into JSON format
  // You must have Jackson in your classpath
  return sum;
 }
}
This controller declares two mappings:
/main/ajax/add (GET) - retrieves the add page
/main/ajax/add (POST) - processes the sum
Notice the POST version of the add() will return an Integer but it's also annotated with @ResponseBody. With this annotation added, Spring will automatically convert the returned data to an appropriate response. In our case, it will convert the Integer to a JSON format if you have the Jackson library in your classpath

What is @ResponseBody
The @ResponseBody annotation instructs Spring MVC to serialize .... Spring MVC automatically serializes to JSON because the client accepts that content type.

Underneath the covers, Spring MVC delegates to a HttpMessageConverter to perform the serialization. In this case, Spring MVC invokes a MappingJacksonHttpMessageConverter built on the Jackson JSON processor. This implementation is enabled automatically when you use the mvc:annotation-driven configuration element with Jackson present in your classpath.

Source: http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

Here is the JSP page.

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="/spring-mvc-jquery/resources/js/jquery/jquery-1.4.4.min.js"></script>
 <script type="text/javascript">
     var jq = jQuery.noConflict();
 </script>
 
 <title>Spring MVC - jQuery Integration Tutorial</title>

</head>
<body>

<h3>Spring MVC - jQuery Integration Tutorial</h3>
<h4>AJAX version</h4>

Demo 1
<div style="border: 1px solid #ccc; width: 250px;">
 Add Two Numbers: <br/>
 <input id="inputNumber1" name="inputNumber1" type="text" size="5"> +
 <input id="inputNumber2" name="inputNumber2" type="text" size="5">
 <input type="submit" value="Add" onclick="add()" /> <br/>
 Sum: <span id="sum">(Result will be shown here)</span>
</div>


<script type="text/javascript"> 

function add() {
 jq(function() {
  // Call a URL and pass two arguments
  // Also pass a call back function
  // See http://api.jquery.com/jQuery.post/
  // See http://api.jquery.com/jQuery.ajax/
  // You might find a warning in Firefox: Warning: Unexpected token in attribute selector: '!' 
  // See http://bugs.jquery.com/ticket/7535
  jq.post("/spring-mvc-jquery/krams/main/ajax/add",
     {  inputNumber1:  jq("#inputNumber1").val(),
        inputNumber2:  jq("#inputNumber2").val() },
      function(data){
       // data contains the result
       // Assign result to the sum id
       jq("#sum").replaceWith('<span id="sum">'+ data + '</span>');
     });
 });
}

</script>
</body>
</html>
Notice in the head section, we have included the jQuery library:
<script type="text/javascript" src="/spring-mvc-jquery/resources/js/jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
     var jq = jQuery.noConflict();
</script>
We've also added a jQuery.noConflict(). This basically allows us to use any variable to represent a jQuery call. By default it uses $ to call its function. By assigning jQuery.noConflict() to a variable, we can now use this new variable to call all our jQuery functions. For more info, see http://api.jquery.com/jQuery.noConflict/

Let's examine our JSP page. Notice it contains two parts: the HTML part that shows the input, and the JavaScript part that handles the AJAX.

HTML part
Demo 1
<div style="border: 1px solid #ccc; width: 250px;">
 Add Two Numbers: <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">(Result will be shown here)</span>
</div>
This is a simple form that takes two numbers. When the Add button is clicked, the JavaScript add() function is called.

JavaScript part
<script type="text/javascript"> 

function add() {
 jq(function() {
  // Call a URL and pass two arguments
  // Also pass a call back function
  // See http://api.jquery.com/jQuery.post/
  // See http://api.jquery.com/jQuery.ajax/
  // You might find a warning in Firefox: Warning: Unexpected token in attribute selector: '!' 
  // See http://bugs.jquery.com/ticket/7535
  jq.post("/spring-mvc-jquery/krams/main/ajax/add",
     {  inputNumber1:  jq("#inputNumber1").val(),
        inputNumber2:  jq("#inputNumber2").val() },
      function(data){
       // data contains the result
       // Assign result to the sum id
       jq("#sum").replaceWith('<span id="sum">'+ data + '</span>');
     });
 });
}

</script>

The add() function is a wrapper to jQuery's post() function. (For more info about post(), see See http://api.jquery.com/jQuery.post/) It takes any number of arguments and a callback function to handle the result. Here we're including the values from two input text fields: inputNumber1 and inputNumber2. Then we use an inner function function(data){...} to handle the result.
function(data){
       // data contains the result
       // Assign result to the sum id
       jq("#sum").replaceWith('<span id="sum">'+ data + '</span>');
     });
Here the sum is the name of the HTML element we assigned earlier in the HTML part:
Sum: <span id="sum">(Result will be shown here)</span>

Let's run our application and check the result.

To access the Add page, enter the following URL in your browser:
http://localhost:8080/spring-mvc-jquery/krams/main/ajax/add

Here's the result:

The result is displayed on the same page. There's no need to create another page just to view the result.

We're almost done with our tutorial. Now we need to add the required XML configurations to enable Spring MVC.

Let's start with the web.xml

web.xml
<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>/krams/*</url-pattern>
 </servlet-mapping>

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

In the web.xml we declared a servlet-name spring. By convention, we must declare a spring-servlet.xml as well.

spring-servlet.xml
<!-- Declare a view resolver -->
 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
      p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

By convention, we must declare an applicationContext.xml as well.

applicationContext.xml
<!-- 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="org.krams.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 /> 

Conclusion

That's it. We've completed our application. We've managed to build a simple Spring MVC 3 application with AJAX capabilities using jQuery. We've also explored how we can return JSON responses using @ResponseBody and the Jackson library

The best way to learn further is to try the actual application.

Download the project
You can access the project site at Google's Project Hosting at http://code.google.com/p/spring-mvc-jquery/

You can download the project as a Maven build. Look for the spring-mvc-jquery.zip in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run

If you want to learn more about Spring MVC and integration with other technologies, feel free to read my other tutorials in the Tutorials section.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3 and jQuery Integration Tutorial ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Friday, January 7, 2011

Spring MVC 3: Using a Document-Oriented Database - MongoDB

In this tutorial we will create a simple Spring MVC 3 application that uses a document-oriented database for its persistence layer. We will be using MongoDB as our database. We will explore and discover how easy it is to integrate MongoDB with Spring MVC 3. Our application is a simple CRUD service for managing a list of Persons. We will provide facilities for adding, deleting, editing, and viewing of all registered persons. This tutorial is similar with my other database integration tutorials: Spring 3 MVC - JDBC Integration Tutorial, Spring 3 MVC - Hibernate 3: Using Annotations Integration Tutorial

Note: An updated version of this tutorial is now accessible at Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB (Part 1)

What is MongoDB?
MongoDB (from "humongous") is a scalable, high-performance, open source, document-oriented database. Written in C++, MongoDB features:
  • Document-oriented storage
  • Full Index Support
  • Replication & High Availability
  • Scale horizontally without compromising functionality.
  • Rich, document-based queries.
  • Atomic modifiers for contention-free performance.
  • Flexible aggregation and data processing.
  • Store files of any size without complicating your stack.
  • Enterprise class support, training, and consulting available.

Source: http://www.mongodb.org/
In a nutshell MongoDB uses JSON instead of SQL There's no static schema to create. All schemas are dynamic, meaning you create them on-the-fly. You can try a real-time online shell for MongoDB at http://try.mongodb.org/. Visit the official MongoDB site for a through discussion.

In order to complete this tutorial, you will be required to install a copy of MongoDB. If you don't have a MongoDB yet, grabe one now by visiting this link http://www.mongodb.org/display/DOCS/Quickstart. The installation is really easy.

Let's begin by defining our MongoDBFactory.

MongoDBFactory
package org.krams.tutorial.mongo;

import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.mongodb.Mongo;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoException;

/**
 * A simple factory for returning a MongoDB
 */
public class MongoDBFactory {
 
 protected static Logger logger = Logger.getLogger("mongo");
 
 private static Mongo m;
 
 // Make sure no one can instantiate our factory
 private MongoDBFactory() {}
 
 // Return an instance of Mongo
 public static Mongo getMongo() {
  logger.debug("Retrieving MongoDB");
  if (m == null) {
   try {
    m = new Mongo( "localhost" , 27017 );
   } catch (UnknownHostException e) {
    logger.error(e);
   } catch (MongoException e) {
    logger.error(e);
   }
  }
  
  return m;
 }
 
 // Retrieve a db
 public static DB getDB(String dbname) {
  logger.debug("Retrieving db: " + dbname);
  return getMongo().getDB(dbname);
 }
 
 // Retrieve a collection
 public static DBCollection getCollection(String dbname, String collection) {
  logger.debug("Retrieving collection: " + collection);
  return getDB(dbname).getCollection(collection);
 }
}
MongoDBFactory is simply a factory for retrieving a single instance of your database via getDB() and a single instance of your collection via getCollection(). This is a custom class we created to simplify the retrieval of these items. If you prefer to retrieve them manually instead of using this MongoDBFactory, you're free to do so. Here's an example on how you may retrieve them manually:

Remember our database and collections will be created on-the-fly. Our schema will be based on our domain Person object.

Person


Let's now define a Person service for performing CRUD functions in our application.

PersonService

This service defines our basic CRUD system. We have the following public methods:
getAll() - for retrieving all persons
edit() - for editing
delete() - for deleting
add() - for adding
get() - for retrieving single person
We also have the following private methods:
init() - for initializing our database
getDBObject() - for retrieving a single Mongo object
The database is initialized once in the PersonService's constructor through the init() method:


Notice we're creating a dynamic JSON schema here with the following format:
{  
   id:'',
   firstName:'',
   lastName:'',
   money:''
}
Let's complete our Spring MVC application. We need to define a controller.

MainController

This controller declares the following mappings:
/persons - for retrieving all persons
/persons/add (GET) - displays the Add New form
/persons/add (POST) - saves the new person
/persons/delete - deletes an existing person
/persons/edit (GET) - displays the Edit form
/persons/edit (POST) - saves the edited person

Each mapping delegates the call to the PersonService. When the PersonService is done processing, the controller then forwards the request to a JSP page that displays a confirmation message. Here are the JSP pages.

personspage.jsp

editpage.jsp

addpage.jsp

editedpage.jsp

addedpage.jsp

deletedpage.jsp

To finish our Spring MVC application, we need to declare a couple of required XML configurations.

To enable Spring MVC we need to add it in the web.xml

web.xml

Take note of the URL pattern. When accessing any pages in our MVC application, the host name must be appended with
/krams
In the web.xml we declared a servlet-name spring. By convention, we must declare a spring-servlet.xml as well.

spring-servlet.xml

By convention, we must declare an applicationContext.xml as well.

applicationContext.xml

 
 
 
 
 
 
  
That's all we need to do to integrate MongoDB and Spring MVC.

Let's examine what happens in the MongoDB console whenever we perform a particular action in our MVC application. When the application is initially run, we mentioned that it will drop and create a new collection. So MongoDB's console should reflect this action as well. Here's the log:
Fri Jan  7 00:34:10 [initandlisten] connection accepted from 127.0.1.1:42747 #1
Fri Jan  7 00:34:10 [conn1] CMD: drop mydb.mycollection
Fri Jan  7 00:34:10 [conn1] building new index on { _id: 1 } for mydb.mycollection
Fri Jan  7 00:34:10 [conn1] done for 0 records 0secs
It did drop and create our collection.

Now let's access the main page that shows all registered persons. To access the main page, enter the following URL in your browser:
http://localhost:8080/spring-mvc-mongodb/krams/main/persons
Here's what you should see:

Here's the log from MongoDB's console:
Fri Jan  7 00:36:48 [initandlisten] connection accepted from 127.0.1.1:53424 #2
Let's edit the first record in our list by clicking the Edit link. We will be redirected to the Edit Person page:

Here's the log from MongoDB's console:
Fri Jan  7 00:39:07 [initandlisten] connection accepted from 127.0.1.1:53427 #3
After editing the person and submitting the changes, we should see the following page:

However the MongoDB's console didn't change. When return back to the main page, we see the edited person.

Let's stop our application, and check the output from MongoDB's console:
Fri Jan  7 00:47:50 [conn3] end connection 127.0.1.1:53427
Fri Jan  7 00:47:50 [conn1] end connection 127.0.1.1:42747
Fri Jan  7 00:47:50 [conn2] end connection 127.0.1.1:53424
It ended three connections which is logical because we made three connections.

That's it. We've managed to create a simple Spring MVC 3 application that uses MongoDB for its database. We've also seen the benefits of a document-oriented database when we created the schema dynamically.

The best way to learn further is to try the actual application.

Download the project
You can access the project site at Google's Project Hosting at http://code.google.com/p/spring-mvc-mongodb/

You can download the project as a Maven build. Look for the spring-mvc-mongodb.zip in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run

If you want to learn more about Spring MVC and integration with other technologies, feel free to read my other tutorials in the Tutorials section.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3: Using a Document-Oriented Database - MongoDB ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share