Struts 2 CRUD Example using jQuery JSON and JDBC


This Struts 2 tutorial will show you how to create CRUD operation using jQuery. jQuery provides getJSON() method for handling the actions.

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

The getJSON() method is used to get JSON data using an AJAX HTTP GET request.

Syntax

$(selector).getJSON(url,data,success(data,status,xhr));

url URL to send the request.

data- Data to be sent to the server.

success(data,status,xhr)- Function to run if the request succeeds.

– mandatory

JavaScript Snippet

Register JS

function registerUser() {
	var uname = $("#uname").val();
	var udeg = $("#udeg").val();
	var uemail = $("#uemail").val();
	var upass = $("#upass").val();
	var dataURL = "uname=" + uname + "&udeg=" + udeg + "&uemail=" + uemail + "&upass=" + upass;
	$.getJSON("registeruser.action", dataURL, function(data) {
		var ht = data.msg;
		$("#resp").html(ht);
	});
}

Report JS

function report() {		
	$.getJSON("report.action", function(data) {
		var tblData="";
		$.each(data.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);
	});
}

Previous Record JS

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

Update JS

function updateNewRecord() {
	var newDataURL = "uname=" + $("#uname").val() + "&uemail="
			+ $("#uemail").val() + "&upass=" + $("#upass").val() + "&udeg="
			+ $("#udeg").val() + "&hiddenuemail=" + $("#hiddenuemail").val();
	$.getJSON("updateuser.action", newDataURL, function(data) {
		var ht = data.msg;
		$("#resp").html(ht);
	});
}

Delete JS

function deleteUser(that) {
	var delDataURL = "uemail=" + $(that).parent().prev().prev().prev().text();
	$.getJSON("deleteuser.action", delDataURL, function(data) {
		if (data.msg === "Delete Successful") {
			alert(data.msg)
			$(that).closest('tr').remove();
		} else {
			alert(data.msg)
		}
	});
}

Software/Library Used

  1. Eclipse IDE
  2. Tomcat 8 Server
  3. JDK 8
  4. MySQL Database
  5. jQuery
  6. Bootstrap

Note: The response to be sent to jQuery is of type JSON, to handle it you must need struts2-json-plugin-2.x.x.jar.

Project Structure in Eclipse

Struts 2 CRUD Example using jQuery JSON and JDBC

Create Table in Database

We need to create a table in our database to store the user information.

struts2crud.sql
CREATE TABLE `struts2crud` (
  `uname` VARCHAR(25) DEFAULT NULL,
  `uemail` VARCHAR(50) NOT NULL,
  `upass` VARCHAR(25) DEFAULT NULL,
  `udeg` VARCHAR(25) DEFAULT NULL,
  PRIMARY KEY (`uemail`)
);

Define Filter

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

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>Struts2CRUDjQueryJSON</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<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>
</web-app>

Create DAO Class

This class will communicate with the database. In this class I have created all the methods for connecting to the database, insert data into the database, fetch data from the database, etc.

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

Create the getter and setters of parameters.

EmpBean.java
package org.websparrow.bean;

public class EmpBean {
        // Generate Getters and Setters...
	private String uname, uemail, upass, udeg;
}

Create Action Classes

We need to create the four action classes for every operation to make it simple.

1- Register Action Class

In this class, we get the user information and save into the database. If data inserted successfully display success message otherwise error message.

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;
        // Generate 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

This class will fetch all the stored data from database and display on JSP. If data is available in database display it else displays No Data Available.

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

In this class, We will fetch the previous data from the database and update the new data in 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;
        // Generate Getters and Setters...
	private String uname, udeg, uemail, upass, msg, 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 select data 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 JSP Pages

Create the JSP pages that interact with the users.

1- Index JSP

On this page user will fill out all the 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();
		var dataURL = "uname=" + uname + "&udeg=" + udeg + "&uemail=" + uemail
				+ "&upass=" + upass;
		$.getJSON("registeruser.action", dataURL, function(data) {
			var ht = data.msg;
			$("#resp").html(ht);
		});
	}
</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

This page display all the data that retrieved from the database and update the user record and delete the record.

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 report
	function report() {		
		$.getJSON("report.action", function(data) {
			var tblData="";
			$.each(data.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);
		});
	}
	
// function for fetch old data in 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 update new records
	function updateNewRecord() {		
		var newDataURL="uname="+$("#uname").val()+"&uemail="+$("#uemail").val()+"&upass="+$("#upass").val()+
		                "&udeg="+$("#udeg").val()+"&hiddenuemail="+$("#hiddenuemail").val();		
		$.getJSON("updateuser.action",newDataURL, function(data){			
			var ht= data.msg;
			$("#resp").html(ht);
		});
	}

// function for delete selected record
	function deleteUser(that) {		
		var delDataURL="uemail="+$(that).parent().prev().prev().prev().text();
		$.getJSON("deleteuser.action",delDataURL, function(data){			
			if(data.msg==="Delete Successful"){
				alert(data.msg)
				$(that).closest('tr').remove();				
			} else{
				alert(data.msg)
			}			
		});		
	}
</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="register.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 Action Classes in strusts.xml

Map your action class in struts.xml. You 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 JSON and JDBC

report screen

Struts 2 CRUD Example using jQuery JSON and JDBC

update screen

Struts 2 CRUD Example using jQuery JSON and JDBC

delete screen

Struts 2 CRUD Example using jQuery JSON and JDBC

Similar Posts

About the Author

Websparrow
I like sharing my experiments and ideas with everyone by writing articles on the latest technological trends.