Struts 2 CRUD Example using jQuery Ajax and JDBC


On this page, we will create a simple Struts2 CRUD operation using jQuery ajax. The ajax() method is used to perform an AJAX (asynchronous HTTP) request.

In this example, we will insert the user information into the database, fetch information from the database, update user information into the database and delete the user information.

Similar Post- Struts 2 CRUD Example using jQuery JSON and JDBC

Syntax

$.ajax({
		type : "Method name(GET/POST)",
		url : "url map to the action class",
		data : "data to be sent on the server", 
		success : {"Message on success"},
		error : {"Message on error"}}
    });

Software/Library Used

  1. Eclipse IDE
  2. Tomcat 8
  3. JDK 8
  4. jQuery 3
  5. Bootstrap 3

Required Dependencies

You can directly add all core JARs of struts2.x.x in your application or add below to your pom.xml if your application maven based.

pom.xml
<dependencies>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-core</artifactId>
		<version>2.3.16.2</version>
	</dependency>
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts2-json-plugin</artifactId>
		<version>2.3.16.2</version>
	</dependency>
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.42</version>
	</dependency>
</dependencies>

Note: You must have struts2-json-plugin-2.x.x.jar file in your project, it allows you to serialize the Action class attribute which has getter and setter into a JSON object.

Project Structure in Eclipse

Struts 2 CRUD Example using jQuery Ajax and JDBC

Define the Struts 2 filter

Before starting the code we need define struts 2 filters in web.xml.

web.xml
<filter>
	<filter-name>struts2</filter-name>
	<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

Create DAO Class

This class will contain all the method for handling the user information into the database.

Admin.java
package org.websparrow.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Admin {

	// method for creating connection
	public static Connection myconnection() throws Exception {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/websparrow", "root", "");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String registerUser(String uname, String uemail, String upass, String udeg) throws SQLException, Exception {
		try {
			String sql = "INSERT INTO STRUTS2CRUD VALUES (?,?,?,?)";
			PreparedStatement ps = myconnection().prepareStatement(sql);
			ps.setString(1, uname);
			ps.setString(2, uemail);
			ps.setString(3, upass);
			ps.setString(4, udeg);
			ps.executeUpdate();
			return "Registration Successful";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		} finally {
			if (myconnection() != null) {
				myconnection().close();
			}
		}
	}

	public ResultSet report() throws SQLException, Exception {
		ResultSet rs = null;
		try {
			String sql = "SELECT UNAME,UEMAIL,UPASS,UDEG FROM STRUTS2CRUD";
			PreparedStatement ps = myconnection().prepareStatement(sql);
			rs = ps.executeQuery(sql);
			return rs;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			if (myconnection() != null) {
				myconnection().close();
			}
		}
	}

	public String updateUser(String uname, String uemail, String upass, String udeg, String hiddenuemail)
			throws SQLException, Exception {
		try {
			String sql = "UPDATE STRUTS2CRUD SET UNAME=?,UEMAIL=?,UPASS=?, UDEG=? WHERE UEMAIL=?";
			PreparedStatement ps = myconnection().prepareStatement(sql);
			ps.setString(1, uname);
			ps.setString(2, uemail);
			ps.setString(3, upass);
			ps.setString(4, udeg);
			ps.setString(5, hiddenuemail);
			ps.executeUpdate();
			return "Update Successful";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		} finally {
			if (myconnection() != null) {
				myconnection().close();
			}
		}
	}

	public String deleteUser(String uemail) throws SQLException, Exception {
		try {
			String sql = "DELETE FROM STRUTS2CRUD WHERE UEMAIL=?";
			PreparedStatement ps = myconnection().prepareStatement(sql);
			ps.setString(1, uemail);
			ps.executeUpdate();
			return "Delete Successful";
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		} finally {
			if (myconnection() != null) {
				myconnection().close();
			}
		}
	}
}

Create Bean Class

Define all parameters and generate its getters and setters…

EmpBean.java
package org.websparrow.bean;

public class EmpBean {
	
	// generate getters and setters...
	private String uname, uemail, upass, udeg;
	
}

Create Action Classes

To make it simple I have separated all the action class.

1- Register Action Class

This class will take the input from the form and save it into the database.

RegisterAction.java
package org.websparrow.action;

import org.websparrow.dao.Admin;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {
	private static final long serialVersionUID = -3827439829486925185L;
	// getters and setters...
	private String uname, udeg, uemail, upass, msg;
	Admin dao = null;

	@Override
	public String execute() throws Exception {
		dao = new Admin();
		msg = dao.registerUser(uname, uemail, upass, udeg);
		return "REGISTER";
	}
}

2- Report Action Class

In this class, we will fetch all the saved information from the database and return to JSP page.

ReportAction.java
package org.websparrow.action;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.websparrow.bean.EmpBean;
import org.websparrow.dao.Admin;

import com.opensymphony.xwork2.ActionSupport;

public class ReportAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	ResultSet rs = null;
	EmpBean bean = null;
	List<EmpBean> beanList = null;
	Admin admin = new Admin();

	@Override
	public String execute() throws Exception {
		try {
			beanList = new ArrayList<EmpBean>();
			rs = admin.report();
			if (rs != null) {
				while (rs.next()) {
					bean = new EmpBean();
					bean.setUname(rs.getString("UNAME"));
					bean.setUemail(rs.getString("UEMAIL"));
					bean.setUpass(rs.getString("UPASS").replaceAll("(?s).", "*"));
					bean.setUdeg(rs.getString("UDEG"));
					beanList.add(bean);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "REPORT";
	}

	public List<EmpBean> getBeanList() {
		return beanList;
	}

	public void setBeanList(List<EmpBean> beanList) {
		this.beanList = beanList;
	}
}

3- Update Action Class

Update action class update the new user information into the database.

UpdateAction.java
package org.websparrow.action;

import org.websparrow.dao.Admin;

import com.opensymphony.xwork2.ActionSupport;

public class UpdateAction extends ActionSupport {
	private static final long serialVersionUID = -3827439829486925185L;
	// getters and setters
	private String uname, udeg, uemail, upass, msg;
	private String hiddenuemail;
	Admin dao = null;

	@Override
	public String execute() throws Exception {
		dao = new Admin();
		msg = dao.updateUser(uname, uemail, upass, udeg, hiddenuemail);
		return "UPDATE";
	}
}

4- Delete Action Class

Delete the selected user information from the database.

DeleteAction.java
package org.websparrow.action;

import org.websparrow.dao.Admin;

import com.opensymphony.xwork2.ActionSupport;

public class DeleteAction extends ActionSupport {
	private static final long serialVersionUID = -3827439829486925185L;
	private String uemail, msg;
	Admin dao = null;

	@Override
	public String execute() throws Exception {
		dao = new Admin();
		msg = dao.deleteUser(uemail);
		return "DELETE";
	}

	public String getUemail() {
		return uemail;
	}

	public void setUemail(String uemail) {
		this.uemail = uemail;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}

Create View Components

Create the JSP pages.

1- Index JSP
This JSP page will take user information.

index.jsp
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
	function registerUser() {
		var uname = $("#uname").val();
		var udeg = $("#udeg").val();
		var uemail = $("#uemail").val();
		var upass = $("#upass").val();
		$.ajax({
			type : "POST",
			url : "registeruser.action",
			data : "uname=" + uname + "&udeg=" + udeg + "&uemail=" + uemail	+ "&upass=" + upass,
			success : function(data) {
				var ht = data.msg;
				$("#resp").html(ht);
			},
			error : function(data) {
				alert("Some error occured.");
			}
		});
	}
</script>
</head>
<body>
	<nav class="navbar navbar-default">
		<div class="container">
			<div class="navbar-header">
				<a class="navbar-brand" href="/">CRUD</a>
			</div>
			<ul class="nav navbar-nav">
				<li>
					<a href="register.jsp">Register</a>
				</li>
				<li>
					<a href="report.jsp">Report</a>
				</li>
			</ul>
		</div>
	</nav>
	<div class="container">
		<div class="col-lg-5">
			<div class="row">
				<div class="col-xs-6 col-sm-6 col-md-6">
					<div class="form-group">
						<input type="text" name="uname" id="uname" class="form-control input-sm" placeholder="Full Name">
					</div>
				</div>
				<div class="col-xs-6 col-sm-6 col-md-6">
					<div class="form-group">
						<input type="text" name="udeg" id="udeg" class="form-control input-sm" placeholder="Designation">
					</div>
				</div>
			</div>
			<div class="form-group">
				<input type="text" name="uemail" id="uemail" class="form-control input-sm" placeholder="Email">
			</div>
			<div class="form-group">
				<input type="password" name="upass" id="upass" class="form-control input-sm" placeholder="Password">
			</div>
			<button onclick="registerUser();" type="button" class="btn btn-success btn-block">Register</button>
			<div class="text-center" id="resp" style="margin-top: 14px;"></div>
		</div>
	</div>
</body>
</html>

2- Report JSP
In this JSP page, we will show the all saved user information and update the new user information and delete it.

report.jsp
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
// function for fetching user information from database
	function report() {		
		$.ajax({			
			type:"GET",
			url:"report.action",
			success: function(result){
				var tblData="";
				$.each(result.beanList, function() {					
					tblData += "<tr><td>" + this.uname + "</td>" + 
					"<td>" + this.uemail + "</td>" + 
					"<td>" + this.upass + "</td>" + 
					"<td>" + this.udeg + "</td>" +
					"<td>"+
					"<button onclick='fetchOldRecord(this);' class='btn btn-sm btn-info' data-toggle='modal' data-target='#updateModal'>Update</button>"+
					"<button onclick='deleteUser(this);' class='btn btn-sm btn-danger'>Delete</button>"+
					"</td></tr>" ;
				});
				$("#tbody").html(tblData);
			},
			error: function(result){
				alert("Some error occured.");
			}
		});
	}
	
	// function for fecthing old information into the form
	function fetchOldRecord(that){		
		   $("#uname").val($(that).parent().prev().prev().prev().prev().text());
		   $("#uemail").val($(that).parent().prev().prev().prev().text());
		   $("#upass").val("");
		   $("#udeg").val($(that).parent().prev().text());
		   $("#hiddenuemail").val($(that).parent().prev().prev().prev().text());
       	}
	
	// function for updating new information into database
	function updateNewRecord() {
		$.ajax({
			type:"POST",
			url:"updateuser.action",
			data:"uname="+$("#uname").val()+"&uemail="+$("#uemail").val()+"&upass="+$("#upass").val()+
            	 "&udeg="+$("#udeg").val()+"&hiddenuemail="+$("#hiddenuemail").val(),
            success:function(result){
            	var ht= result.msg;
    			$("#resp").html(ht);
            },
            error: function(result){
            	alert("Some error occured.");
            }
		});	
	}
	
	// function for deleting user information from database
	function deleteUser(that) {	
		$.ajax({
			type:"POST",
			url:"deleteuser.action",
			data:"uemail="+$(that).parent().prev().prev().prev().text(),
			success: function(data){
				if(data.msg==="Delete Successful"){
					alert(data.msg)
					$(that).closest('tr').remove();
					
				} else{
					alert(data.msg)
				}
			},
			error:function(data){
				alert("Some error occured.");
			}
		});
	}
</script>
</head>
<body onload="report();">
	<nav class="navbar navbar-default">
		<div class="container">
			<div class="navbar-header">
				<a class="navbar-brand" href="/">CRUD</a>
			</div>
			<ul class="nav navbar-nav">
				<li>
					<a href="index.jsp">Register</a>
				</li>
				<li>
					<a href="report.jsp">Report</a>
				</li>
			</ul>
		</div>
	</nav>
	<div class="container">
		<table class="table table-bordered">
			<thead>
				<tr class="bg-info">
					<th>Name</th>
					<th>Email</th>
					<th>Password</th>
					<th>Designation</th>
					<th>Action</th>
				</tr>
			</thead>
			<tbody id="tbody">
			</tbody>
		</table>
	</div>
<div class="container" id="updateBlock">
		<div class="modal fade" id="updateModal" role="dialog">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal">×</button>
						<h4 class="modal-title">Update New Information</h4>
					</div>
					<div class="modal-body">
						<div class="row">
							<div class="col-xs-6 col-sm-6 col-md-6">
								<div class="form-group">
									<input type="text" name="uname" id="uname" class="form-control input-sm" placeholder="Full Name">
								</div>
							</div>
							<div class="col-xs-6 col-sm-6 col-md-6">
								<div class="form-group">
									<input type="text" name="udeg" id="udeg" class="form-control input-sm" placeholder="Designation">
								</div>
							</div>
						</div>
						<div class="form-group">
							<input type="text" name="uemail" id="uemail" class="form-control input-sm" placeholder="Email">
							<input type="hidden" name="hiddenuemail" id="hiddenuemail">
						</div>
						<div class="form-group">
							<input type="password" name="upass" id="upass" class="form-control input-sm" placeholder="Password">
						</div>
						<button onclick="updateNewRecord();" class="btn btn-info btn-block">Update</button>
						<div id="resp" class="text-center" style="margin-top: 13px;"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
</body>
</html>

Map the Action Classes

Now map your action class in struts.xml. We will need to set package extends="json-default" result type is json.

struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="default" extends="json-default">
		<action name="registeruser" class="org.websparrow.action.RegisterAction">
			<result name="REGISTER" type="json"></result>
		</action>
		<action name="report" class="org.websparrow.action.ReportAction">
			<result name="REPORT" type="json"></result>
		</action>
		<action name="updateuser" class="org.websparrow.action.UpdateAction">
			<result name="UPDATE" type="json"></result>
		</action>
		<action name="deleteuser" class="org.websparrow.action.DeleteAction">
			<result name="DELETE" type="json"></result>
		</action>
	</package>
</struts>

Output:

Now everything is all set, deploy the project on your web server.

register screen

Struts 2 CRUD Example using jQuery Ajax and JDBC

report screen

Struts 2 CRUD Example using jQuery Ajax and JDBC

update screen

Struts 2 CRUD Example using jQuery Ajax and JDBC

delete screen

Struts 2 CRUD Example using jQuery Ajax and JDBC

Video Demonstration


Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.