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!

Step 1
Download Eclipse software from Click Here

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`)
)
Step 2
Create a fresh project right click and select New -> Dynamic Web Project

Step 3
Give your project name.

After finish the project will create with support files.

Step 4
Now go to Java Resources -> src right click new select package.

I have created three packages controls(servlets), model(Logic) and dao data access object

Step 5
Adding external JARS files into WEB-INF -> lib folder. I have included those in download WAR file.

Step 6
Now right click on the package select New -> Class

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;
}
}
}
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;
}
}
}
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;
}
}
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.

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();
}
}
}
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>
<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

Select tomcat version, if not download Tomcat 7.0

Step 11
Adding project to Tomcat server.

You can dowload the WAR file and import into your Eclipse IDE. Run this project at http://localhost:8080/FirstProject/index.jsp
Great! Good post! thanks for sharing! :)
ReplyDeleteI think JAX-RS would have been a better fit than using a servlet
ReplyDeleteYou should try DWR. You can call java methods directly through javascript
ReplyDeleteit is better to use a persistance unit to avoid data base actions and configuration.
ReplyDeletehttp://localhost:8080/FirstProject/index.jsp
ReplyDeletethis link not working
Awesome post thanks for sharing this post :)
ReplyDeleteAwesome example, and gooooooooooooosh it still looks a pain
ReplyDeleteNice Post, Well described
ReplyDeletewow great job...explained very well
ReplyDeleteJava now here?, very, very good tutorial!!
ReplyDeleteNice Can Give Some Idea and tuterials for htaccess (url rewriting in php).
ReplyDeleteThanks
Nice Post, Keep your Good Work
ReplyDeleteHi, 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?
ReplyDeleteWow, cool, I just found it in your blog.. :D nice tutorial..
ReplyDeleteVery good tutorial!
ReplyDeleteNice tutorial Srinivas, Loved it and helped me a lot!!
ReplyDeleteNice tutorial, loved it :)
ReplyDeletevery useful post.
ReplyDeletewow java tutorial cool
ReplyDeleteWell done. please provide more tutorial of J2EE if you can .....
ReplyDeleteMuy buen tutorial .. Exelente .. Gracias!!
ReplyDeleteAriel Macintosh™
Good tutorial...but it looks really complicated comparing with Jquery+PHP+MYSQL... :)
ReplyDeleteYou need to improve your coding standards, remember in java the first letter of method should be a lower case.
ReplyDeleteAlso 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
ya its wonderful coding working properly to me
ReplyDeleteI 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?
ReplyDeleteIt work, thx you! I used to Postman extension on CHrome instead of using file jsp to request server!
ReplyDeleteThanks.. Pls continue tutorials on J2EE.. very helpful
ReplyDeleteProfessional MVC approach...this is exactly how a pure j2ee application should be built.
ReplyDeleteThanks & continue tutorials on J2EE ;)
ReplyDeletethe jQuery file showing error, without that its showing the index page but not submitting input
ReplyDeleteAwesome ! especially the simplistic but effective approach..
ReplyDeleteGood. Well explained with patience :)
ReplyDeletethanks so much... well explained. nice visuals, makes learning easier and more exciting
ReplyDeleteNice work. Was searching for this. Thanks for detailing.
ReplyDeletethanks for your tutor.. :)
ReplyDeleteGreat JAVA tutorial for beginners.
ReplyDeleteThanks alot.
Please write one restful service to upload a file containing data to import into mysql server.
ReplyDeleteKeep getting this error: 'Uncaught ReferenceError: POST is not defined(…)'
ReplyDeleteIs there something missing or a typo?