Struts 2 Fetch Records From Database

The database can be connected with struts applications to retrieve data using JDBC.

Struts-Fetch Records From Database example:

Create the database and create the table in it:

Create any database using sql command and create the table in it and insert some records in it to be fetched in the struts application.

Create database userdb;  // create the database with any name.


use userdb;                      // select the created database.


Create table usertb(Id int, Name varchar(20), Password varchar(20), Email varchar(20));                  // Create the table in database.


desc usertb;              // desc command is used to check table structure.


INSERT INTO `userdb`.`usertb` (`Id`, `Name`, `Password`, `Email`) VALUES ('1', 'Sanket', 'Sanket123', 'Sanket@123');


INSERT INTO `userdb`.`usertb` (`Id`, `Name`, `Password`, `Email`) VALUES ('2', 'Ram', 'Ram123', 'Ram@123');


INSERT INTO `userdb`.`usertb` (`Id`, `Name`, `Password`, `Email`) VALUES ('3', 'Shyam', 'Shyam123', 'Shyam@123');

To get input from the user create the index.jsp file:

The index.jsp page has heading User Section with a link to view all user records with display name View All User Records after clicking on the link it will redirect to FetchRecords class having action name viewrecords.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %>  
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Index page</title>
</head>
<body>
<h3>User Section</h3>
<a href="viewrecords">View All User Records</a>
</body>
</html>

Create display.jsp file to denote success:

The display.jsp page is used to display All Records. It displays Id, name, password and email of all users in the database. It will display all user data in fieldset. It displays labels with values for particular properties.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="/struts-tags" prefix="s" %>  
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display page</title>
</head>
<body>


<h3>All Records:</h3>
<s:iterator  value="list">
<fieldset>
Id:<s:property value="id"/><br/>
Name:<s:property value="name"/><br/>
Password:<s:property value="password"/><br/>
Email:<s:property value="email"/><br/>
</fieldset>
</s:iterator>
</body>
</html>

Create the class to establish a connection with the database:

Using JDBC establish a connection with the database. Use sql query to fetch all records from the database and iterate them and store them in the list.

import java.sql.*;
import java.util.ArrayList;




public class FetchRecords 
{
ArrayList<User> list=new ArrayList<User>();


public ArrayList<User> getList() 
         {
return list;
}
public void setList(ArrayList<User> list)
          {
this.list = list;
}


public String execute()
          {
try
           {
            Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb","root","");  


PreparedStatement ps=con.prepareStatement("select * from usertb");
ResultSet rs=ps.executeQuery();
while(rs.next())
                                 {
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
user.setEmail(rs.getString(4));
list.add(user);
}
con.close();
}
                      catch(Exception e)
                     {
                           e.printStackTrace();
                     }

return "success";
   }
}

Create the java class User.java:

The Java class User.java contains id, name, password, email fields with their getter and setters. It is the class used to set and get values for the fields.

public class User 
{
private int id;
private String name, password, email;


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 getPassword() 
{
return password;
}
public void setPassword(String password) 
{
this.password = password;
}
public String getEmail() 
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
}

Construct struts.xml file:

In the struts.xml file, make the entry of the action class and link for it and result pages. The result determines what browser will display after the execution of the action. Results have optional names like success and error.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>


<package name="anbc" extends="struts-default">
<action name="viewrecords" class="FetchRecords">
<result name="success">display.jsp</result>
</action>
</package>


</struts> 

web.xml file is created inside WEB-INF folder in WebContent folder:

The web.xml file in the WEB-INF folder specify how elements are processed. The entry of FilterDispatcher is done in the web.xml file. /* specifies all urls will be parsed. This task is done by struts filter.

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>StrutsDatabase</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.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>

Output:

In order to run the application, right-click on the project -> Click on the option Run As -> then select Run on Server. It will show a heading User Section and link to view all records with the display name View All User Records.

Struts-Fetch Records From Database

After Clicking on View All User Records link it will show all users from the database.

Struts-Fetch Records From Database