Jul 01, 2013, by admin
Hi in this post we are going to see how to convert records data into JSON data format and display JSON data feed using Jquery
Database
Sample database messages table contains two columns msg_id and message.
Step 1
Create a new package called dto (Data Transaction Objects).
Right click on src -> New and then select Package.
Give Package name and click finish.
Step 2
Now you have to create a Class, right click on dto -> New – Class
MessageObjects.java
Here you have declare all transaction objects, in this tutorial transaction objects are msg_id and message
package dto;
public class MessageObjects
{
//Message Objects
private String msg_id;
private String message;
//Getters and Setters
}
Step 3
You have to generate Getters and Setters, just right click on the code.
Goto Source and select Generate Getters and Setters
The follow popup window will appear, now select all transaction objects and click Ok.
Automatically Eclipse will generate so code. This system very useful, if sometimes we have large number of transaction objects.
Step 4
For JSON data format you have to copy gson.jar into library folder. Download code contains these JAR files.
Step 5
Data Access Object(dao) Package
Project.java
Create a method GetMessages with Arraylist datatype, using select statement getting results from messages table. Binding results into messageData object.
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dto.MessageObjects;
public class Project
{
public String InsertMessage(Connection connection, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Previous Post
}
public ArrayList GetMessages(Connection connection,HttpServletRequest request,HttpServletResponse response) throws Exception
{
ArrayList messageData = new ArrayList();
try
{
PreparedStatement ps = connection.prepareStatement(“SELECT msg_id,message FROM messages ORDER BY msg_id DESC”);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
MessageObjects messageObject = new MessageObjects();
messageObject.setMsg_id(rs.getString(“msg_id”));
messageObject.setMessage(rs.getString(“message”));
messageData.add(messageObject);
}
return messageData;
}
catch(Exception e)
{
throw e;
}
}
}
Step 6
Model class model package
ProjectManager.java
Here you have to write the business logic eg: User session validation
package model;
import java.sql.Connection;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Project;
import dto.MessageObjects;
public class ProjectManager {
public String InsertMessage(Connection connection, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//Previous Post
}
public ArrayList GetMessages(Connection connection, HttpServletRequest request,
HttpServletResponse response) throws Exception {
ArrayList messages = null;
try {
// Here you can validate before connecting DAO class, eg. User session condition
Project project= new Project();
messages=project.GetMessages(connection, request, response);
}
catch (Exception e) {
throw e;
}
return messages;
}
}
Step 7
Create servlet class in controls package.
GetMessages.java
Converting messageData object data to JSON data format. Add servlet class mapping in web.xml file inside WEB-INF directory.
package controls;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import dao.Database;
import model.ProjectManager;
import dto.MessageObjects;
@WebServlet(“/GetMessages”)
public class GetMessages extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetMessages() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try
{
Database database= new Database();
ProjectManager projectManager= new ProjectManager();
ArrayList messagesData = null;
Connection connection = database.Get_Connection();
messagesData = projectManager.GetMessages(connection, request, response);
Gson gson = new Gson();
String messages = gson.toJson(messagesData);
out.println(“{“Messages”:”+messages+”}”);
}
catch (Exception ex)
{
out.println(“Error: ” + ex.getMessage());
}
finally
{
out.close();
}
}
}
JSON Output for messages data.
{
“Messages”:[
{
“msg_id”:”3″,
“message”:”Everything is possible. ”
},
{
“msg_id”:”2″,
“message”:”9lessons Programming Blog http://9lessons.info”
},
{
“msg_id”:”1″,
“message”:”Make People fall in love with Your Ideas”
}
]
}
Step 8
Final step display JSON data using Jquery.
index.jsp
Using $.ajax calling GetMessages servlet then reading JSON data with $.each method and appending data into content div.
<script type=”text/javascript” src=’js/jquery.min.js’></script>
<script type=’text/javascript’>
$(document).ready(function()
{
$.ajax
({
type: “GET”,
url: “GetMessages”,
dataType:”json”,
success: function(data)
{
if(data.Messages.length)
{
$.each(data.Messages, function(i,data)
{
var msg_data=”<div id=’msg”+data.msg_id+”‘>”+data.message+”</div>”;
$(msg_data).appendTo(“#content”);
});
}
else
{
$(“#content”).html(“No Results”);
}
}
});
$(‘#UpdateButton’).click(function()
{
// Previous Post
});
return false;
});
});
</script>
//HTML Code
<textarea id=’Message’></textarea><br/>
<input type=’button’ value=’ Update ‘ id=’UpdateButton’/>
<div id=’content’></div>
Click here to download war file
Click here to download source file
Reference site
http://www.9lessons.info