Java MySQL Insert Record using Jquery.
Wall Script
Wall Script
Wednesday, July 25, 2012

Java MySQL Insert Record using Jquery.

If you know Java concepts, you can easily understand any kind of language very quickly. If you want to became a good programmer, I strongly suggest start with J2EE programming. I heard that many people feels that it's though After long time I decided to write about J2EE programming with Jquery in a simple and better understanding way, hope you like it. Thanks!

Menu Design with JSON Data.

Download War File    Download Project Source

Step 1
Download Eclipse software from Click Here
Java MySQL Insert Record using Jquery.

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

Step 2
Create a fresh project right click and select New -> Dynamic Web Project
Java MySQL Insert Record using Jquery.

Step 3
Give your project name.
Java MySQL Insert Record using Jquery.

After finish the project will create with support files.
Java MySQL Insert Record using Jquery.

Step 4
Now go to Java Resources -> src right click new select package.
Java MySQL Insert Record using Jquery.

I have created three packages controls(servlets), model(Logic) and dao data access object
Java MySQL Insert Record using Jquery.

Step 5
Adding external JARS files into WEB-INF -> lib folder. I have included those in download WAR file.
Java MySQL Insert Record using Jquery.

Step 6
Now right click on the package select New -> Class
Java MySQL Insert Record using Jquery.

Database.java
Create MySQL database connection just modify database name.
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database
{
public Connection Get_Connection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/database_name";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
return connection;
}
catch (SQLException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
}

Project.java
Main data access object file inserting record into messages table.
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Project
{
public String InsertMessage(Connection connection, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String message = null;
try {
message = request.getParameter("message");
PreparedStatement ps = connection.prepareStatement("INSERT INTO messages(message) VALUES(?)");
ps.setString(1, message);
int rs = ps.executeUpdate();
if (rs>0) {
return message;
} else {
return null;
}

} catch (Exception e) {
throw e;
}
}

}

Step 7
Now creating a manager class inside model package here you have to write the business logic.

ProjectManager.java
Here input message value validating here.
package model;

import java.sql.Connection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.Project;

public class ProjectManager
{
public String InsertMessage(Connection connection, HttpServletRequest request,
HttpServletResponse response) throws Exception {
String message = null;
try {
message = request.getParameter("message");
if(message != null && message !="" && message.length()>0)
{
Project project= new Project();
message=project.InsertMessage(connection, request, response);
}
} catch (Exception e) {
throw e;
}
return message;
}
}

Step 8
Now creating servlet file inside controls package.
Java MySQL Insert Record using Jquery.

InsertMessage.java
Getting request.
package controls;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

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 model.ProjectManager;
import dao.Database;

/**
* Servlet implementation class InsertMessage
*/
@WebServlet("/InsertMessage")
public class InsertMessage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(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();
String message = null;
Connection connection = database.Get_Connection();
message= projectManager.InsertMessage(connection, request, response);
if (message!=null)
{
out.println("<div>"+message+"</div>");
}
else
{
out.println("false");
}
}
catch (Exception ex)
{
out.println("Error: " + ex.getMessage());
}
finally
{
out.close();
}
}

}

Step 9
View index.jsp page will send the request to InsertMessage

index.jsp
View File
<script type="text/javascript" src='js/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('#UpdateButton').click(function()
{
var MSG = $("#Message").val();
var dataString = 'message='+ MSG;
$.ajax({
type: "POST",
url: "InsertMessage",
data: dataString,
cache: false,
success: function(data)
{
$("#Message").val('');
$("#content").prepend(data);
$("#Message").focus();
}
});
return false;
});
});
</script>
//HTML Code
<textarea id='Message'></textarea><br/>
<input type='button' value=' Update ' id='UpdateButton'/>
<div id='content'></div>

Step 10
Add Tomcat Server
Java MySQL Insert Record using Jquery.

Select tomcat version, if not download Tomcat 7.0
Java MySQL Insert Record using Jquery.

Step 11
Adding project to Tomcat server.
Java MySQL Insert Record using Jquery.

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

39 comments:

  1. Great! Good post! thanks for sharing! :)

    ReplyDelete
  2. I think JAX-RS would have been a better fit than using a servlet

    ReplyDelete
  3. You should try DWR. You can call java methods directly through javascript

    ReplyDelete
  4. it is better to use a persistance unit to avoid data base actions and configuration.

    ReplyDelete
  5. http://localhost:8080/FirstProject/index.jsp

    this link not working

    ReplyDelete
  6. Awesome post thanks for sharing this post :)

    ReplyDelete
  7. Awesome example, and gooooooooooooosh it still looks a pain

    ReplyDelete
  8. wow great job...explained very well

    ReplyDelete
  9. Java now here?, very, very good tutorial!!

    ReplyDelete
  10. Nice Can Give Some Idea and tuterials for htaccess (url rewriting in php).
    Thanks

    ReplyDelete
  11. Hi, great post, just wanted to know how can i connect to a mysql db which is part of wamp server, the connectURL will be same?

    ReplyDelete
  12. Wow, cool, I just found it in your blog.. :D nice tutorial..

    ReplyDelete
  13. Nice tutorial Srinivas, Loved it and helped me a lot!!

    ReplyDelete
  14. very useful post.

    ReplyDelete
  15. Well done. please provide more tutorial of J2EE if you can .....

    ReplyDelete
  16. Muy buen tutorial .. Exelente .. Gracias!!

    Ariel Macintosh™

    ReplyDelete
  17. Good tutorial...but it looks really complicated comparing with Jquery+PHP+MYSQL... :)

    ReplyDelete
  18. You need to improve your coding standards, remember in java the first letter of method should be a lower case.
    Also it is not necessary to import the servlet api .jar file in eclipse, only you need to define the web container.
    Anyway your tutorial is good.

    Manuel Loayza

    ReplyDelete
  19. ya its wonderful coding working properly to me

    ReplyDelete
  20. I just started learning java and finally i got the first tutorial my old jquery teacher. :) Thanks Srinavas. Moreover I have a question that what is that at step5 External Jars why we need it and as name suggests its about mysql connection so which kind of this jar how it will help us in connecting with mysql? when we also creating connection in our code file?

    ReplyDelete
  21. It work, thx you! I used to Postman extension on CHrome instead of using file jsp to request server!

    ReplyDelete
  22. Thanks.. Pls continue tutorials on J2EE.. very helpful

    ReplyDelete
  23. Professional MVC approach...this is exactly how a pure j2ee application should be built.

    ReplyDelete
  24. Thanks & continue tutorials on J2EE ;)

    ReplyDelete
  25. the jQuery file showing error, without that its showing the index page but not submitting input

    ReplyDelete
  26. Awesome ! especially the simplistic but effective approach..

    ReplyDelete
  27. Good. Well explained with patience :)

    ReplyDelete
  28. thanks so much... well explained. nice visuals, makes learning easier and more exciting

    ReplyDelete
  29. Nice work. Was searching for this. Thanks for detailing.

    ReplyDelete
  30. Please write one restful service to upload a file containing data to import into mysql server.

    ReplyDelete
  31. Keep getting this error: 'Uncaught ReferenceError: POST is not defined(…)'

    Is there something missing or a typo?

    ReplyDelete

mailxengine Youtueb channel
Make in India
X