Java Servlet Send & Receive JSON Using jQuery.ajax()

This is a complete example showing how to send jQuery.Ajax() POST request containing data in JSON format to the server, and how to receive this JSON content, parse it and map it into Java objects in the server “servlet” side. Also, we will see how to send the list of all received data back to the client in JSON format and how the client can parse this data and display it.

java-servlet-json

Objectives:

  • How to send jQuery.ajax() POST request with data in JSON format?
  • How to receive JSON data in Java servlet, parse it and map it into Java objects?
  • How to send data back to the client in JSON format too?

Environment & Tools:

  • Eclipse
  • Maven
  • Jetty (jetty-maven-plugin 9.x) or any other server supporting servlet 3.0
  • FireFox or Google Chrome

Libraries:

  • Java Servlet API 3.1
  • Jackson
  • jQuery 1.9

( 1 ) Project Structure

java-servlet-json-project

( 2 ) Server-Side

  • Article.java
  • JSONServlet.java
  • web.xml

Received “JSON” data will be mapped to Article object.

package com.hmkcode.vo;

import java.util.LinkedList;
import java.util.List;

public class Article {

	private String title;
	private String url;
	private List<String> categories;
	private List<String> tags;

//getters & setters 
}
  • /src/main/java/com/hmkcode/JSONServlet.java

This servlet class will receive data sent by client in JSON format. It will parse it and map it into Java object. Then mapped object “Article” will be added to the List<Article> which will be sent to the client after converting it to JSON again.

package com.hmkcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkcode.vo.Article;

public class JSONServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	// This will store all received articles
	List<Article> articles = new LinkedList<Article>();

	/***************************************************
	 * URL: /jsonservlet
	 * doPost(): receives JSON data, parse it, map it and send back as JSON
	 ****************************************************/
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	        throws ServletException, IOException{

		// 1. get received JSON data from request
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String json = "";
		if(br != null){
			json = br.readLine();
		}

		// 2. initiate jackson mapper
    	ObjectMapper mapper = new ObjectMapper();

    	// 3. Convert received JSON to Article
    	Article article = mapper.readValue(json, Article.class);

		// 4. Set response type to JSON
		response.setContentType("application/json");		    

    	// 5. Add article to List<Article>
		articles.add(article);

		// 6. Send List<Article> as JSON to client
    	mapper.writeValue(response.getOutputStream(), articles);
	}
}
  • /src/main/webapp/WEB-INF/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_3_0.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
id="WebApp_ID" version="3.0">
  <display-name>Java Servlet JSON</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
  	<servlet-name>jsonservlet</servlet-name>            
  	<servlet-class>com.hmkcode.JSONServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>jsonservlet</servlet-name>
  	<url-pattern>/jsonservlet</url-pattern>
  </servlet-mapping>
</web-app>

( 3 ) Client-Side

  • index.html
  • myfunctions.js
  • /src/main/webapp/index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Java Servlet JSON</title>
<script src="js/jquery.1.9.1.min.js"></script>

<!-- bootstrap just to have good looking page -->
<link href="bootstrap/css/bootstrap.css" type="text/css" rel="stylesheet" />

<!-- we code these -->
<script src="js/myfunctions.js"></script>

</head>

<body>

	<h1 style="text-align:center">Java Servlet Send & Receive JSON<br></h1> 

	<!-- article inputs -->
	<div class="article" style="margin:10px;">
		<div class="input-prepend">
			<span class="add-on">Title</span>
			<input class="span4" id="title" name="title" type="text" placeholder="Article Title...">
		</div>
		<br/>
		<div class="input-prepend">
			<span class="add-on">URL</span>
			<input class="span4" id="url" name="url" type="text" placeholder="http://...">
		</div>
		<br/>
		<div class="input-prepend">
			<span class="add-on">Categories</span>
			<input class="span2" id="categories" name="categories" type="text" placeholder="category1;category2;...">
		</div>
		<br/>
		<div class="input-prepend">
			<span class="add-on">Tags</span>
			<input class="span2" id="tags" name="tags" type="text" placeholder="tag1;tag2;...">
		</div>
		<p>
			<button class="btn btn-primary" type="button" onclick="sendAjax()">Add</button>
		</p>
	</div>

	<!-- display all articles -->
	<div style="width:700px;padding:20px;S">
		<h5 style="text-align:center"><i style="color:#ccc"><small>Articles</small></i></h5>

		<table id="added-articles" class="table">
			<tr>
				<th>Title</th>
				<th>Categories</th>
				<th>Tags</th>
			</tr>
		</table>
	</div>
</body> 
</html>
  • /src/main/webapp/js/myfunctions.js
function sendAjax() {

	// get inputs
	var article = new Object();
	article.title = $('#title').val();
	article.url = $('#url').val();
	article.categories = $('#categories').val().split(";");
	article.tags = $('#tags').val().split(";");

	$.ajax({
		url: "jsonservlet",
		type: 'POST',
		dataType: 'json',
		data: JSON.stringify(article),
		contentType: 'application/json',
		mimeType: 'application/json',

		success: function (data) {
        	$("tr:has(td)").remove();

        	$.each(data, function (index, article) {

                var td_categories = $("<td/>");
                $.each(article.categories, function (i, tag) {
                	var span = $("<span class='label label-info' style='margin:4px;padding:4px' />");
                	span.text(tag);
                	td_categories.append(span);
                });

                var td_tags = $("<td/>");
                $.each(article.tags, function (i, tag) {
                	var span = $("<span class='label' style='margin:4px;padding:4px' />");
                	span.text(tag);
                	td_tags.append(span);
                });

                $("#added-articles").append($('<tr/>')
                		.append($('<td/>').html("<a href='"+article.url+"'>"+article.title+"</a>"))
                		.append(td_categories)
                		.append(td_tags)
                );

            }); 
        },
		error:function(data,status,er) {
			alert("error: "+data+" status: "+status+" er:"+er);
		}
	});
}

( 4 ) Run

To run this sample code using Maven you just need to download the source code and execute the following command

>mvn jetty:run

Source Code @ GitHub

Related posts from Java Tutorial