Table of contents
1.
Introduction🧑🏻‍🎓
2.
Pre-requisites🧐
3.
An Example for Fetching All Records of a Table🤔
3.1.
Create index.jsp for Invoking Action (Optional)🤔
3.1.1.
Index.jsp
3.2.
Create the Action Class🤔
3.2.1.
Register.java
3.3.
Create the Class to Represent the Table🤔
3.3.1.
User.java
3.4.
Create struts.xml🤔
3.4.1.
struts.xml
3.5.
Create View Component🤔
3.5.1.
welcome.jsp
4.
Frequently Asked Questions
4.1.
How can we create a custom interceptor in Struts 2?
4.2.
What is the purpose of the global-forwards tag in struct-config.xml?
4.3.
What is the purpose of the plug-in tag in struct-config.xml?
4.4.
What class of struts is responsible to converts data types from strings and vice versa?
4.5.
What is the return type of execute() method in struts2?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Struts 2 Fetching All Records of a Table

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction🧑🏻‍🎓

Struts 2 is a beautiful, adaptable framework for building Java web applications that are business-ready. This framework's goal is to speed up the entire application development process, from creation to deployment and ongoing maintenance. We can also fetch all the records of a table using an iterator tag in Struts 2. 

OG image Struts 2

In the following article, we will take an example by which we will understand the working of the iterator tag in fetching the records of a table. Let’s go! 🫡

Pre-requisites🧐

To retrieve all of the records, we have all of the records stored in a collection (using List), and struts2's iterator tag is used to display the collection's contents.

Here, we'll assume that you have a table called ninja335 with records in your Oracle database. The table's query is:

CREATE TABLE  "NINJA335"   
( 
"ROLL_NO” NUMBER,   
    "NAME" VARCHAR2(5000),   
    "ADDRESS" VARCHAR2(5000),   
    "PHONE" VARCHAR2(5000),   
     CONSTRAINT "NINJA335_PK" PRIMARY KEY ("ID") ENABLE
) 

An Example for Fetching All Records of a Table🤔

Fetching records image

We are creating five pages in this example :

  1. Action of invoking index.jsp.
  2. Register.java is used to save table data in a collection.
  3. User.java is used to display the table.
  4. For defining the action and outcome, use struts.xml.
  5. For the view component to display records, use welcome.jsp.

Create index.jsp for Invoking Action (Optional)🤔

To activate the action, a link is created on this jsp page. However, you can manually call the action class.

Index.jsp

<a href="viewtherecords">View All Records in the table</a>  

Create the Action Class🤔

The execute method and ArrayList object are both included in this action class.

Register.java

package com.codingninjas;  
import java.sql.*;  
import java.util.ArrayList;  
  
public class FetchTheRecords {  
ArrayList<Ninja> recList=new ArrayList<Ninja>();  
  
public ArrayList<Ninja> getTheList() {  
    return recList;  
}  
public void setTheList(ArrayList<Ninja> recList) {  
    this.recList = recList;  
}  
public String execute(){  
 try{  
  Class.forName("oracle.jdbc.driver.OracleDriver");  
  Connection con=DriverManager.getConnection(  
    "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
              
  PreparedStatement ps=con.prepareStatement("select * from ninja335");  
  ResultSet rs=ps.executeQuery();  
  
  while(rs.next()){  
   Ninja ninja=new Ninja();  
   user.setRoll_no(rs.getInt(1));  
   user.setName(rs.getString(2));  
   user.setAddress(rs.getString(3));  
   user.setPhone(rs.getString(4));  
   list.add(ninja);  
  }  
  
  con.close();  
 }catch(Exception e){e.printStackTrace();}  
          
 return "success";  
}  
}  
You can also try this code with Online Java Compiler
Run Code

Create the Class to Represent the Table🤔

This is the simple bean class containing four fields.

User.java

package com.codingninjas;  
  
public class Ninja {  
private int Roll_no;  
private String name, address, phone ;  
//getters and setters  }  
You can also try this code with Online Java Compiler
Run Code

Create struts.xml🤔

This xml file defines action and result.

struts.xml

<?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="viewtherecords" class="com.codingninjas.FetchRecords">  
<result name="success">displayrecords.jsp</result>  
</action>  
</package>  
  
</struts>      

Create View Component🤔

It is a simple jsp file displaying the information of the user.

welcome.jsp

<%@ taglib uri="/struts-tags" prefix="s" %>  
  
<h3>All Records:</h3>  
<s:iterator  value="list">  
<fieldset>  
<s:property value="Roll_no"/><br/>  
<s:property value="name"/><br/>  
<s:property value="address"/><br/>  
<s:property value="phone"/><br/>  
</fieldset>  
</s:iterator>  
You can also try this code with Online Java Compiler
Run Code

 

We hope you understood everything about struts 2 fetching all records of a table.🤗

Frequently Asked Questions

How can we create a custom interceptor in Struts 2?

The Interceptor interface only has to be extended in order to create a custom interceptor.

What is the purpose of the global-forwards tag in struct-config.xml?

This section links a name to a page in your web application. This term can be used to refer to the page itself. By using this, you can avoid hardcoding URLs on your website.

What is the purpose of the plug-in tag in struct-config.xml?

This section specifies where your properties files—which contain prompts and error messages—can be found for Struts.

What class of struts is responsible to converts data types from strings and vice versa?

By overriding the two methods convertFromString() and convertToString(), the StrutsTypeConverter class instructs Struts about converting Environment to a String and vice-versa.

What is the return type of execute() method in struts2?

The framework has pre-defined return values for the action's execute() method, including SUCCESS, ERROR, INPUT, LOGIN, and NONE.

Conclusion

This article taught us how to fetch a table's records in a Struts 2 framework. We began with a brief introduction to the method, followed by a detailed example.

After reading about fetching of records in Struts 2, refer to Struts 2 documentationStruts Tutorial for beginnersStruts 2 Intro, and 15 Best Java frameworks to use in 2022-Coding Ninjas or a deeper understanding of Struts 2 development and other related topics.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Do upvote our blog to help other ninjas grow.

Happy Learning Ninja! 🥷     

ThankYou Image
Live masterclass