Create, Read, Update and Delete – CRUD Examples with JDBC & Struts 2

The Struts 2 framework is used to develop an MVC-based web application using JDBC. It was initially created by Craig McClanahan and donated to the Apache Foundation in May 2000 and Struts 1.0 was released in June 2001.

The current stable release of Struts is Struts 2.3.16.1, developed on March 2, 2014. This Struts 2 tutorial covers all the topics of the Struts 2 Framework with simplified examples for beginners and experienced coders.

Struts 2 Framework

A diagram of how the Struts 2 Framework works

Struts 2 and 1 both are used to developed MVC-based web applications. It’s a combination of web works and Struts 1. We are using Struts 2 with Spring, JSP, Hibernates.

struts2 = webwork + struts1

Struts 2 provides some classes like POJO-based class, Validation Support class, AJAX support class Integration support to various frameworks such as Hibernate, Spring, Tiles, etc, support to various result types such as Freemarker, Velocity, JSP, etc.

In other words, Struts 2 provides many features that were not in Struts 1.

The important features of Struts 2 are as follows:

1.Configurable MVC components

2.POJO based actions

3.AJAX support

4.Integration support

5.Various Result Types

6.Various Tag support

7.Theme and Template support

A diagram of the Struts 2 architecture

1) Configurable MVC components

In the Struts 2 frameworks, we provide all the components (view components and action) information in the struts.XML file.

Add any Action change only Struts file.

2) POJO based actions

In Struts 2, the action class is POJO (Plain Old Java Object) i.e. a simple java class. Here, you are not forced to implement any interface or inherit any class.

3) AJAX support

Struts 2 provides support to Ajax technology. It is used to make asynchronous requests i.e. it doesn’t block the user. It sends only required field data to the server-side, not all of it. So, it makes the performance fast.

4) Integration Support

We can simply integrate the Struts 2 application with hibernate, spring, tiles etc. frameworks.

5) Various Result Types

We can use JSP, free marker, velocity, etc. technologies as the result in Struts 2.

6) Various Tag support

Struts 1 only provides Custom Tags like Tiles, but Struts 2 provides UI tags, Data tags, and Control Tag. Additionally, Struts 2 Provided Interceptor.

7) Theme and Template support

Struts 2 provides three types of theme support: XHTML, simple, and css_xhtml. The XHTML is the default theme of Struts 2. Themes and templates can be used for a common look and feel.

(CRUD) Example using JDBC-> Software/Library Used Eclipse IDE Tomcat 8 JDK 8 MySQL Database struts2 core jars MySQL connector jar.

Project Structure in Eclipse

Project Structure in Eclipse

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 to 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>Struts2CRUD</display-name>
	<welcome-file-list>
		<welcome-file>register.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 in 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 {
	
	 
// we need a connection for sql and mysql. first add ac driver and connecect your host like local host

	public static Connection getConnection() throws Exception {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection("jdbc:mysql://localhost/websparrow", "root", "");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	// method for save user data in database

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

	// method for fetch saved user data

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

	// method for fetch old data to be update

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

	// in this method update data on update.jsp page 

	public int updateUserDetails(String uname, String uemail, String upass, String udeg, String uemailhidden)
			throws SQLException, Exception {
		getConnection().setAutoCommit(false);
		int i = 0;
		try {
			String sql = "UPDATE STRUTS2CRUD SET UNAME=?,UEMAIL=?,UPASS=?,UDEG=? WHERE UEMAIL=?";
			PreparedStatement ps = getConnection().prepareStatement(sql);
			ps.setString(1, uname);
			ps.setString(2, uemail);
			ps.setString(3, upass);
			ps.setString(4, udeg);
			ps.setString(5, uemailhidden);
			i = ps.executeUpdate();
			return i;
		} catch (Exception e) {
			e.printStackTrace();
			getConnection().rollback();
			return 0;
		} finally {
			if (getConnection() != null) {
				getConnection().close();
			
 }
		}
	}

	// method for delete the record

	public int deleteUserDetails(String uemail) throws SQLException, Exception {
		getConnection().setAutoCommit(false);
		int i = 0;
		try {
			String sql = "DELETE FROM STRUTS2CRUD WHERE UEMAIL=?";
			PreparedStatement ps = getConnection().prepareStatement(sql);
			ps.setString(1, uemail);
			i = ps.executeUpdate();
			return i;
		} catch (Exception e) {
			e.printStackTrace();
			getConnection().rollback();
			return 0;
		} finally {
			if (getConnection() != null) {
				getConnection().close();
			}
		}
	}
}

Create Bean Class

Create the getter and setters of parameters.

EmpBean.java

package org.websparrow.bean;

public class EmpBean {
	
	// generate getter and setters right click mouse and go to generate getter and setter 
	private String uname, uemail, upass, udeg;
	int srNo;
}

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 it into the database. If data inserted successfully display success message another 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 = 2139116285823340125L;
private String uname, uemail, upass, udeg;
private String msg = “”;
Admin admin = null;
int ctr = 0;

@Override
public String execute() throws Exception {
admin = new Admin();

try {
ctr = admin.registerUser(uname, uemail, upass, udeg);
if (ctr > 0) {
msg = “Registration Successfull”;
} else {
msg = “Some error”;
}
} catch (Exception e) {
e.printStackTrace();
}
return “REGISTER”;
}

public void setUname(String uname) {
this.uname = uname;
}

2- Report Action Class

Report Action class fetch all data from database and user show in overhand.

Conclusion

In this blog, I have developed a small window application using the Struts framework by performing insert, update, and delete operations on data in MySQL and SQL.

Moreover, the application is developed using the JDBC driver and Struts 2 jars. I hope this post would be informative for you and if you have any queries, you can post your comments in the comment section. Thank you!


 

Leave a Comment