Back to: Java Struts Tutorials
Struts 2 Database with Examples
In this article, I am going to discuss Struts 2 Database with Examples. Please read our previous article where we discussed Struts 2 Uploading Files. In this demo, we will be using JDBC to connect a Struts2 application to a MySQL database. Before programming the application in Eclipse, you will need to set up MySQL.
What is JDBC?
JDBC stands for Java Database Connectivity. It is an API (Application Programming Interface) provided by Java that allows Java programs to interact with databases. JDBC enables developers to write Java code to perform various database operations such as connecting to a database, executing SQL queries, retrieving and manipulating data, and managing database transactions.
The JDBC API provides a set of classes and interfaces that define methods and properties to establish a connection with a database, send SQL statements, retrieve and update data, and handle errors. It acts as a bridge between Java applications and different database management systems (DBMS) such as MySQL, Oracle, SQL Server, and others.
Here are some key Components and Concepts in JDBC:
- DriverManager: It is a class that manages the establishment of a connection with a database. It helps in loading the appropriate JDBC driver for the DBMS being used.
- Connection: The Connection interface represents a connection to a specific database. It allows executing SQL statements and managing transactions.
- Statement: The Statement interface enables executing SQL statements and retrieving results. There are different types of statements available, such as Statement, PreparedStatement, and CallableStatement.
- ResultSet: The ResultSet interface represents the result of a database query. It provides methods to retrieve and manipulate the data returned by a query.
- JDBC Drivers: JDBC drivers are implementations of the JDBC API provided by database vendors. They handle the communication between Java programs and the underlying database.
To use JDBC in a Java program, you need to include the JDBC driver for your chosen database system in your classpath and import the necessary JDBC classes. Then, you can establish a connection, execute SQL statements, retrieve data, and perform other database operations using the JDBC API.
Overall, JDBC is a widely used technology in Java development for database connectivity and data manipulation, allowing Java applications to interact with various databases in a standardized and platform-independent manner.
Setup MySQL
Step 1: Download, install, and set up MySQL. You may use MySQL Workbench or MySQL shell. Here we will use MySQL shell:
Step 2: Create a database using the CREATE DATABASE command:
Check that the database has been created:
Step 3: Set the newly created struts2 database to the current database:
Step 4: Create a table called User:
Programming Struts2 Application
Step 1: Create a new maven project in Eclipse. We will use Maven to manage the dependencies of struts2. This way, we do not have to import JARs.
Remember to set the packaging to war. This is because we shall be deploying a web application.
Finally, click on the finish button to create the project. The following project directories need to be created:
Step 2: Initially, the pom.xml file should contain the following content:
Modify pom.xml to add the required dependencies and the build configuration:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.dotnet</groupId> <artifactId>strutex</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>6.1.2.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>6.1.2.1</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts-taglib</artifactId> <version>1.3.10</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>8.0.33</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.11.0</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build> </project>
Step 3: In the src/main/webapp directory, create a new file called index.jsp. Add the following content to the file:
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1" pageEncoding = "ISO-8859-1"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Login</title> </head> <body> <form action = "studentAction" method = "post"> Enter student id: <input type = "text" name = "id"/> <input type = "submit" value = "Show details"/> </form> </body> </html>
Step 4: In the src/main/webapp directory, create a new file called success.jsp. Add the following content to the file:
<%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Student Details</title> </head> <body> Student name: <s:property value = "name"/> Student email: <s:property value = "email"/> </body> </html>
Step 5: In the src/main/webapp directory, create a new file called error.jsp. This file will be displayed if there is an error when the file upload is in progress. Add the following content to the file:
<%@ page contentType = "text/html; charset = UTF-8" %> <%@ taglib prefix = "s" uri = "/struts-tags" %> <html> <head> <title>Error</title> </head> <body> Student details not found! </body> </html>
Step 6: In the src/main/java directory, create a new file called StudentAction.java. The file contains the Java action code. This code should be executed when the “Show details” button is clicked. Add the following content to the file:
package com.dotnet; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.opensymphony.xwork2.ActionSupport; public class StudentAction extends ActionSupport { private int id; private String name, email; public String execute() { String ret = ERROR; Connection conn = null; try { String URL = "jdbc:mysql://localhost/struts2"; Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(URL, "root", "DotNet23"); String SQL = "SELECT name, email FROM Students WHERE id = ?"; PreparedStatement ps = conn.prepareStatement(SQL); ps.setLong(1, id); ResultSet r = ps.executeQuery(); while (r.next()) { name = r.getString(1); email = r.getString(2); ret = SUCCESS; } } catch (Exception e) { ret = ERROR; e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (Exception e2) {} } } return ret; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
The execute() function retrieves the details of the student from the database. Based on the outcome of the copy operation, the method returns SUCCESS or ERROR.
Step 7: In the src/main/resources directory, create a new file called struts.xml. The file is responsible for configuring struts2. Add the following content to the file:
<?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> <constant name = "struts.devMode" value = "true" /> <package name = "helloworld" extends = "struts-default"> <action name = "loginAction" class = "com.dotnet.LoginAction" method = "execute"> <result name = "success">/success.jsp</result> <result name = "error">/error.jsp</result> </action> </package> </struts>
Step 8: In the src/main/webapp directory, create a new directory called WEB-INF. In this directory, create a new file called web.xml. This file is responsible for implementing struts2 in the web application. Add the following content to the file:
<?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/web-app_3_0.xsd" id="apache-struts-config-example" version="3.0"> <display-name>Struts Config XML</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.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
Step 9: Enter a value into the database. This value will be later retrieved by the Struts2 application.
Step 10: Compile and execute the program on the Tomcat server. The following page must open in your default web browser:
Enter the student id (which you have entered in the database in step 9) and click on “Show Details…”. The following success webpage must load:
Congratulations! You have successfully connected a database to a struts2 application using JDBC.
In the next article, I am going to discuss Struts 2 Email with Examples. Here, in this article, I try to explain Struts 2 Database with Examples and I hope you enjoy this Struts 2 with Database article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.