Java MySQL JSON Display Records using Jquery.
Wall Script
Wall Script
Monday, August 27, 2012

Java MySQL JSON Display Records using Jquery.

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!

Java JSON Jquery Display Records

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`)
)

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.
Java JSON Jquery Display Records

Give Package name and click finish.
Java JSON Jquery Display Records

Step 2
Now you have to create a Class, right click on dto -> New - Class
Java JSON Jquery Display Records

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.
Java JSON Jquery Display Records

Goto Source and select Generate Getters and Setters
Java JSON Jquery Display Records

The follow popup window will appear, now select all transaction objects and click Ok.
Java JSON Jquery Display Records

Automatically Eclipse will generate so code. This system very useful, if sometimes we have large number of transaction objects.
Java JSON Jquery Display Records

Step 4
For JSON data format you have to copy gson.jar into library folder. Download code contains these JAR files.
Java JSON Jquery Display Records

Step 5
Data Access Object(dao) Package
Java JSON Jquery Display Records

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.
Java JSON Jquery Display Records

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>

Step 9
You can dowload the WAR file and import into your Eclipse IDE. Run this project at http://localhost:8080/SecondProject/index.jsp
web notification

36 comments:

  1. Very good illustrations & Screenshots

    ReplyDelete
  2. This is perfect. Thanks. But there should be more post on j2ee. Currently there are only 3-4 post on j2ee.

    ReplyDelete
  3. Gr8 Job srinivas...! will try it out this evening...! :)

    ReplyDelete
  4. Hi Srinivas,
    Your JEE tutorial is very good! Thanks!

    ReplyDelete
  5. Thanks for the code and thanks for the procedure. It was very clear presentation. Keep posting

    ReplyDelete
  6. Thanks for the code and thanks for the procedure. It was very clear presentation. Keep posting

    ReplyDelete
  7. thanks for this useful information

    ReplyDelete
  8. Thank u very much for great tutorial
    using GSON.

    ReplyDelete
  9. Hi,

    I 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...

    ReplyDelete
  10. Dam u made me very happy....I was searching this for days. Finally got it ..... Thanks

    ReplyDelete
  11. This code is not working coz of errors in jquery.js file under eclipse

    ReplyDelete
  12. org.apache.jasper.JasperException: Unable to compile class for JSP:

    An 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.

    ReplyDelete
  13. This tutorial was a great help. Thank you! :D

    ReplyDelete
  14. I was trying this example

    jquery.min.js -> getting below error

    Multiple markers at this line
    - Missing semicolon

    your help appriciated

    ReplyDelete
  15. I was trying this example and under

    jquery.min.js
    getting below error

    Multiple markers at this line
    - Missing semicolon
    Please help me to resolve this

    ReplyDelete
  16. Hi,

    Its not advisable to share request and response object in DAO. Breaks the MVC pattern

    ReplyDelete
  17. Your tutorials have helped me a lot and i just want to repay you with a little improvement to the javascript part of it.

    http://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

    ReplyDelete
  18. me sale error aqui

    HttpServletResponse response) throws Exception {
    // Previous Post
    }

    ReplyDelete
  19. Very Helpful Tutorial

    ReplyDelete
  20. Not working display error

    Please help.

    ReplyDelete
  21. giving data.Messages.length is undefined

    ReplyDelete
  22. Add servlet class mapping in web.xml file inside WEB-INF directory. WHERE IS this shown?

    ReplyDelete

mailxengine Youtueb channel
Make in India
X