MVC stands for Model-View-Controller, which divides an application into three primary logical parts: the model, the view, and the controller. These parts are created to deal with a particular application development task. Struts 2 is a framework for development. Struts 2 frameworks can be used to create applications. We need to access the database to store and retrieve stored data in applications. Struts offer strong support for JPA/Hibernate integration despite being an MVC framework rather than a database framework. Struts applications can connect to the database via JDBC to store and retrieve data.
This article will cover the steps required for struts 2 database access.
We will understand the Struts 2 database access using an example. In this example, we'll use the Struts Framework to build a user login form and store the data in a MySQL database. Depending on your requirements, you can also use different databases like Oracle, DB2, etc.
Let's learn struts 2 database access with the help of an example.
Creating Database
We are using MySQL as our database in this example. Firstly, we will create a database called 'Code_Studio' and then create a table named 'loginINFO'. Insert some data in the table.
Code:
CREATE TABLE `Code_studio`.`loginINFO` (
`Email_ID` VARCHAR(30) NOT NULL,
`Password` VARCHAR(20) NOT NULL,
`Full_Name` VARCHAR(30) NOT NULL,
PRIMARY KEY( `Email_ID` )
)ENGINE = InnoDB;
INSERT INTO `Code_studio`.`loginINFO` (`Emil_ID`, `Password`, `Full_Name`)
VALUES('ninjas@codingninjas.com', 'CN123', 'Kumar');
Now we have created our database. Let's create the action class.
Create Action
The columns in the database table of columns correspond to the properties in the action class. Email ID, Password, and Full Name are available as String attributes. In the action method, we use the Email ID and Password parameters to determine whether the user is present. If they are, the following screen displays the user's full name. We would send the user back to the login screen if incorrect information is entered.
Below is the LoginINFOAction.java file:
Code:
package com.codingninjas.struts2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class LoginINFOAction extends ActionSupport
{
private String Email_ID;
private String Pass;
private String Full_Name;
public String execute()
{
String ret = Error;
Connection cn = null;
try
{
String URL = "jdbc:mysql://localhost/Code_Studio";
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection(URL, "Sys_name", "Sys_password");
String sql = "SELECT Full_Name FROM loginINFO WHERE";
sql += " Email_ID = ? AND Password = ?";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, Email_ID);
ps.setString(2, Pass);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
name = rs.getString(1);
ret = success;
}
}
catch (Exception e)
{
ret = Error;
}
finally
{
if (cn != null)
{
try
{
cn.close();
}
catch (Exception e)
{
}
}
}
return ret;
}
public String getEmail_ID()
{
return Email_ID;
}
public void setEmail_ID(String Email_ID)
{
this.Email_ID = Email_ID;
}
public String getPassword()
{
return Password;
}
public void setPassword(String Pass)
{
this.Pass = Pass;
}
public String getFull_Name()
{
return Full_Name;
}
public void setFull_Name(String Full_Name)
{
this.name = Full_Name;
}
}
Create Main Page
Next, we will create theindex.jsp JSP file to collect the email id and password. The database will be searched to see if this email id and password are valid.
Now let's construct the success.jsp file, which will be used when the operation returns SUCCESS. If the operation returns an ERROR, however, a different view file will be used.
We hope that this example of creating a user login form in struts has thoroughly cleared your concept of struts 2 database access. This example depicts how a database is accessed to store login details.
Before you go and implement this struts database access concept in your applications, we recommend you go through the following FAQs at once.
Frequently Asked Questions
What is the Action class in Struts2?
The Action class is the controller of the MVC pattern. It responds to user action and returns a result that instructs the Struts view to render.
What is XML-based validation in Struts2?
XML-based validation provides additional validation possibilities, including validation of email, numeric ranges, form fields, expressions, regexes, needed conditions, required strings, string lengths, and others.
Do we need to use a database in all struts applications?
Databases are necessary for applications that search, sort, filter, and present information in response to user online requests.
What is JPA?
Java Persistence API (JPA) is merely a specification that makes object-relational mapping easier in Java applications. It is used to manage relational data.
Conclusion
In this article, we have extensively discussed the details of creating and managing Web application using Struts 2 Database Access.