Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Creating Database
3.
Create Action
4.
Create Main Page 
5.
Create Views
6.
Configuration Files
7.
Frequently Asked Questions
7.1.
What is the Action class in Struts2?
7.2.
What is XML-based validation in Struts2?
7.3.
Do we need to use a database in all struts applications?
7.4.
What is JPA?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts 2 Database Access

Author Nagendra
0 upvote

Introduction

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.

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.

User login form

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;
        }
}
Accessing Database Image

Create Main Page 

Next, we will create the index.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.

Creating Main Page

Code:

<html>
	<head>
     <title>Login</title>
    </head>
    <body>
    	<center>
    		<h1>Welcome to Login Page</h1>
    	</center>
     	<form action="loginINFOaction" method="post" align="center">
         	Email_ID:<br /><input type="text" name="Email_ID" /><br/>
         	Password:<br /><input type="password" name="Password" /><br/>
            <input type="submit" value="Submit" />
        </form>
	</body>
</html>

Output:

Login Page Image

Create Views

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.

Code:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<head>
		<title>Logged In Succesfully</title>
	</head>
    <body>
    Welcome to Coding Ninjas!!
    </body>
</html>

A view file in case of ERROR looks like this:

Code:

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
	<head>
		<title>Invalid Email ID or Password</title>
	</head>
	<body>
		Incorrect Email ID or password provided
	</body>
</html>

Configuration Files

Let's combine everything using the following struts.xml configuration file:

Code:

<?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="Coding Ninjas" extends="struts-default">
        <action name="loginINFOaction" method="execute">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>
Struts 2 Application Created

Output:

welcome to coding ninjas

Output Message:

Output Image

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.

We hope that the blog has helped you enhance your knowledge regarding Struts 2 Database Access. If you would like to learn more about Struts 2 Database, check out the articles on Struts 2, you can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. To practice and improve yourself in the interview, you can also check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blogs to help other ninjas grow. Happy Coding!!

Live masterclass