This is the continuation of my previous Java tutorial Insert Records into MySQL database using Jquery, now I want to explain how to convert records data into JSON data format and display JSON data feed using Jquery. It's simple just follow few steps with Eclipse IDE, hope you understand the Model View Controller pattern Thanks!
Download War File Download Project Source
Database
Sample database messages table contains two columns msg_id and message.
CREATE TABLE `messages`
(
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`message` text,
PRIMARY KEY (`msg_id`)
)
(
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`message` text,
PRIMARY KEY (`msg_id`)
)
Previous Tutorial: Java MySQL Insert Record using Jquery.
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
}
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;
}
}
}
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
{
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;
}
}
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
HttpServletResponse response) throws Exception {
ArrayList
try {
// Here you can validate before connecting DAO class, eg. User session condition
Project project= new Project();
messages=project.GetMessages(connection, request, response);
}
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();
}
}
}
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
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"
}
]
}
"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>
<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>
Step 9
You can dowload the WAR file and import into your Eclipse IDE. Run this project at http://localhost:8080/SecondProject/index.jsp
Great tuto!!
ReplyDeleteYo maneje J2ME
ReplyDeletegr8 job
ReplyDeleteSuper cool!
ReplyDeleteVery good illustrations & Screenshots
ReplyDeletethanks
ReplyDeletegreat work...
ReplyDeleteThis is perfect. Thanks. But there should be more post on j2ee. Currently there are only 3-4 post on j2ee.
ReplyDeleteGr8 Job srinivas...! will try it out this evening...! :)
ReplyDeleteHi Srinivas,
ReplyDeleteYour JEE tutorial is very good! Thanks!
thanks for sharing this :)
ReplyDeleteThanks for the code and thanks for the procedure. It was very clear presentation. Keep posting
ReplyDeleteThanks for the code and thanks for the procedure. It was very clear presentation. Keep posting
ReplyDeleteVery informative
ReplyDeletethanks for this useful information
ReplyDeleteThank u very much for great tutorial
ReplyDeleteusing GSON.
Good One
ReplyDeleteJSON is powerfull!!
ReplyDeleteHi,
ReplyDeleteI tried this tutorial and its working fine, great...! I extended this tutorial and created a servlet which retrieves all messages from the database, not working...
superb presentation .
ReplyDeleteDam u made me very happy....I was searching this for days. Finally got it ..... Thanks
ReplyDeleteThis code is not working coz of errors in jquery.js file under eclipse
ReplyDeleteorg.apache.jasper.JasperException: Unable to compile class for JSP:
ReplyDeleteAn error occurred at line: 17 in the jsp file: /cha.jsp
The method createBarChart3D(String, String, String, CategoryDataset, PlotOrientation, boolean, boolean, boolean) in the type ChartFactory is not applicable for the arguments (String, String, String, JDBCCategoryDataset, PlotOrientation, boolean, boolean, boolean)
14: "com.mysql.jdbc.Driver","root","venkat");
15:
16: dataset.executeQuery( query);
17: JFreeChart chart = ChartFactory .createBarChart3D(
18: "Bar Chart",
19: "id",
20: "score",
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:423)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:317)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:282)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.18 logs.
can you help me for this error it is important for my final year project.
This tutorial was a great help. Thank you! :D
ReplyDeletecan u write it for android
ReplyDeleteI was trying this example
ReplyDeletejquery.min.js -> getting below error
Multiple markers at this line
- Missing semicolon
your help appriciated
I was trying this example and under
ReplyDeletejquery.min.js
getting below error
Multiple markers at this line
- Missing semicolon
Please help me to resolve this
Hi,
ReplyDeleteIts not advisable to share request and response object in DAO. Breaks the MVC pattern
Your tutorials have helped me a lot and i just want to repay you with a little improvement to the javascript part of it.
ReplyDeletehttp://codeviewer.org/view/code:354d
the improvements are that it produces nicer html with only 1 div instead of a div in a div, and it got easier to style with css.
and a reply to the people that has wrote about the semicolon bug. the fix is to just put them there yourself. it will tell you where it needs to be placed, but it works perfectly fine with or without
me sale error aqui
ReplyDeleteHttpServletResponse response) throws Exception {
// Previous Post
}
great job
ReplyDeleteVery Helpful Tutorial
ReplyDeletevery helpful
ReplyDeleteNot working display error
ReplyDeletePlease help.
giving data.Messages.length is undefined
ReplyDeleteAdd servlet class mapping in web.xml file inside WEB-INF directory. WHERE IS this shown?
ReplyDelete