Back to: Java Struts Tutorials
Introduction to Java Struts 2 Framework
In this article, I am going to give a brief Introduction to Java Struts 2 Framework. At the end of this article, you will understand the following pointers in detail.
- Basic MVC Architecture
- Why do Developers care about MVC?
- What are Struts?
- Struts 2 Framework
- Struts 2 Features
- Struts 2 Advantages and Disadvantages
- Why is Struts 2 So Popular?
- Struts 2 based on MVC 2 architecture and its life cycle
- Struts 1.x vs Struts 2.x Differences
Basic MVC Architecture
The MVC (Model-View-Controller) architecture is a software design pattern that separates an application into three interconnected components: the Model, the View, and the Controller. This architectural pattern is commonly used in the development of web applications and GUI-based software. Here’s a brief overview of each component:
- Model: The Model represents the application’s data and business logic. It encapsulates data-related operations, such as data retrieval, storage, validation, and manipulation. The Model component does not directly depend on the View or the Controller.
- View: The View is responsible for presenting the user interface and displaying the data to the users. It receives input from users and communicates with the Controller to update the data as necessary. The View should be as passive as possible, focusing on the presentation layer and not performing any business logic.
- Controller: The Controller acts as an intermediary between the Model and the View. It receives user input from the View and translates it into actions to update the Model and/or the View. The Controller contains the application’s logic and controls the flow of data between the Model and the View. It ensures that the Model and View are decoupled and communicates with them accordingly.
The basic flow in an MVC architecture is as follows:
- The user interacts with the View, such as clicking a button or entering data.
- The View notifies the Controller about the user’s action.
- The Controller receives the input, processes it, and interacts with the Model accordingly.
- The Model performs the necessary operations, such as retrieving or updating data.
- The Model notifies the Controller about the changes in the data.
- The Controller updates the View based on the changes in the Model.
- The updated View is displayed to the user.
- The cycle continues as the user interacts with the View.
The MVC architecture promotes separation of concerns, modularity, and reusability of code. It allows different components to be developed independently, which enhances the maintainability and scalability of the software.
Why do Developers Care about MVC?
MVC is the most used software design pattern in app and web development. The design pattern consists of –
- Model
- View
- Controller
For a better understanding, please have a look at the following diagram.
Let us understand the role and responsibilities of the Model, View, and Controller.
Model: Stores and Manages Data
- It consists of systems’ business logic.
- It contains all the data of the application.
- It represents the state of the application.
- It consists of those classes that have a connection to the database.
- The controller makes a connection with the model, fetches the data, and sends it to the view layer.
- The model connects with the database and stores the data in a database that is connected to it.
View: Graphical User Interface
- It consists of HTML, JSP, etc. into it.
- It represents the UI of the application.
- It is used to show the data that is being fetched from the controller, in turn, it fetches data from model layer classes.
- This view layer shows the data on the UI of the application.
Controller: Brains of the application
- The controller connects the model and view.
- The controller converts inputs from view to fulfill the demand to retrieve/update data in the model.
- The controller receives input from the view and uses logic to convert the input to a demand for the model that grabs the data and the controller passes data to the view from the model back to the user for better display.
What are Struts?
The Struts is an open-source framework for developing Java web applications based on the Model-View-Controller (MVC) design pattern. It provides a structured approach to building web applications by separating the different concerns and promoting code reusability. The main components of the Struts framework are:
- ActionServlet: It acts as the controller in the MVC pattern. It receives requests from clients and delegates the processing to appropriate Action classes.
- Actions: These are Java classes that handle the business logic of the application. They receive input from the users, interact with the model layer (typically through data access objects or services), and determine the appropriate view to display.
- ActionForm: It represents the form or data associated with a specific action. It provides a way to encapsulate and validate the user input. ActionForms are usually populated with data from the request parameters and passed to the Action classes.
- Views: Struts supports various view technologies such as JavaServer Pages (JSP) and Velocity templates. These views are responsible for rendering the output to the users based on the data provided by the Action classes.
- Struts Configuration: The framework relies on an XML configuration file (struts-config.xml) to define the mappings between URLs, Actions, and views. It specifies how the requests are routed to the appropriate Action classes and views.
- Validator Framework: Struts includes a built-in validation framework that allows you to define validation rules for your form inputs. It provides server-side validation and can handle common validation tasks like required fields, data types, and custom validations.
The Struts framework simplifies the development of web applications by providing a standard structure and predefined components. It promotes the separation of concerns, making it easier to maintain and test the code. Struts have been widely used in the Java community, although other frameworks like Spring MVC and JavaServer Faces (JSF) have gained popularity in recent years.
Java Struts 2 Framework
In the realm of Java web application development, frameworks play a crucial role in providing structure, reusability, and efficiency. Among the many frameworks available, Struts 2 has emerged as a popular choice. Struts 2 builds upon the success of its predecessor, Struts 1, and offers enhanced features, improved architecture, and increased flexibility. In this article, we will delve into the Struts 2 framework and explore its key features, benefits, and how it simplifies Java web application development.
Struts 2 is an open-source Java web application framework designed to follow the Model-View-Controller (MVC) architectural pattern. It offers a comprehensive set of components and utilities to facilitate the development of robust and scalable web applications. Struts 2 focuses on simplicity, extensibility, and ease of use, making it a popular choice for developers worldwide.
The Struts 2 framework has emerged as a powerful tool for developing Java web applications. Its adherence to the MVC pattern, convention over configuration approach, and extensive feature set make it an attractive choice for developers. By leveraging the capabilities of Struts 2, developers can streamline their development process, enhance code quality, and deliver robust web applications that meet the demands of modern businesses. Whether you are a seasoned Java developer or new to the ecosystem, exploring Struts 2 can open up a world of possibilities for your web application projects.
Struts2 Framework is a popular web application framework that is based on the MVC design pattern. It is not just a new version of Struts 1, but it is also a full rewrite of the Struts architecture.
Initially, the Webwork framework started with the Struts framework and its motto was to render a well-developed and enhanced framework that is built on Struts in order to design web development easier for the developers. After a certain while, the Struts community and the Webwork framework both joined hands to create the famous Struts2 framework.
Struts 2 Features
Key Features of Java Struts 2 Framework:
- MVC Architecture: Struts 2 follows a clear separation of concerns, with models handling business logic, views responsible for rendering, and controllers managing the flow of data between the two.
- Convention over Configuration: Struts 2 embraces convention over configuration, reducing the need for explicit configuration files. By following naming conventions, developers can streamline their development process and achieve faster time-to-market.
- Action-Based Framework: Actions in Struts 2 are lightweight components responsible for handling user requests. They allow for modular development and enable developers to encapsulate business logic into reusable units.
- Interceptors: Struts 2 employs interceptors to encapsulate cross-cutting concerns such as logging, validation, and security. Interceptors provide a clean and flexible way to intercept and manipulate the request/response cycle.
- Powerful Tag Library: Struts 2 provides a rich set of JSP tags that simplify the creation of dynamic web pages. These tags offer seamless integration with the framework and enable developers to build robust and interactive user interfaces.
- POJO Forms and POJO Actions − You can use any POJO to receive the form input with the help of Struts 2. You can also see any POJO as an Action class.
- Template Support − By using templates, we can support the generation of views.
- Plugin Support − The core Struts2 performances can be enlightened with the help of plugin Support. The number of plugins Support is available for Struts2.
- Profiling − Struts2 provides integral profiling to debug and profile the application. With the help of built-in debugging tools, Struts also provides integrated debugging.
- Easy to Modify Tags − Tag markups in Struts2 can be used by Freemarker templates. JSP or Java knowledge is not required. Basic knowledge of XML, HTML, and CSS knowledge is enough to modify the tags.
- View Technologies − Struts2 has large support for various view options such as Freemarker, JSP, Velocity, and many more.
Advantages of Java Struts 2 Framework:
MVC Architecture:
- Struts 2 adheres to the Model-View-Controller (MVC) architectural pattern.
- This separation of concerns allows for better code organization, maintainability, and scalability.
- The clear separation of business logic, presentation, and control flow enhances code reusability and modularity.
Convention Over Configuration
- Struts 2 embraces convention over configuration, reducing the need for explicit configuration files.
- By following naming conventions, developers can save time and effort in configuration, enabling them to focus more on application development.
Rich Tag Library
- Struts 2 provides a comprehensive set of JSP tags that simplify the creation of dynamic web pages.
- These tags offer seamless integration with the framework and enable developers to build robust and interactive user interfaces with minimal effort.
Interceptors
- Struts 2 employs interceptors, which are pluggable components that intercept and manipulate the request/response processing.
- Interceptors facilitate cross-cutting concerns like logging, validation, and security, making it easier to implement and maintain such functionalities.
Extensibility
- Struts 2 offers a flexible and extensible architecture, allowing developers to customize and extend the framework to meet specific project requirements.
- The plugin framework simplifies the integration of additional functionality, making it possible to leverage third-party libraries and frameworks seamlessly.
Validation Framework
- Struts 2 provides a robust validation framework that simplifies form validation.
- It supports server-side and client-side validations, reducing the effort required to implement and maintain data validation.
- The framework offers a wide range of validation rules and error-handling mechanisms.
Integration Capabilities
- Struts 2 seamlessly integrates with other popular frameworks and technologies such as Hibernate, Spring, and Tiles.
- This compatibility enables developers to leverage existing libraries and frameworks, creating powerful and feature-rich applications.
Simplified ActionForm:
- ActionForms such as POJOs, don’t need to extend from any class or implement any interface.
Annotations Introduced:
- Use of annotation results in length reduction and code complexity. It also includes configuration files for simplicity.
OGNL Integration:
- To fetch data from ValueStack and type conversion that reduces the code, it uses OGNL.
Ajax Support:
- Struts2 tags are enabled by Ajax.
Disadvantages of Java Struts 2 Framework:
Steeper Learning Curve:
- Struts 2, with its rich feature set and comprehensive architecture, has a steeper learning curve compared to simpler frameworks.
- Developers, especially those new to Java web development, may require additional time and effort to grasp the concepts and best practices associated with Struts 2.
Configuration Complexity:
- Although Struts 2 aims to simplify configuration through convention over configuration, complex scenarios often require explicit configuration files.
- Understanding and managing these configuration files can be challenging, particularly for large-scale applications.
Lack of Active Community Support:
- While Struts 2 is a mature framework, its community support and active development have somewhat decreased over time.
- This could result in slower updates, fewer bug fixes, and limited availability of new features.
- However, the existing documentation and resources can still assist developers in troubleshooting issues.
Overhead of Full-Stack Framework:
- Struts 2 is considered a full-stack framework, providing a wide range of features and functionalities.
- However, if an application requires only a subset of these features, the inclusion of the entire framework may introduce unnecessary overhead.
- In such cases, a lighter framework might be a better fit.
Reduced Flexibility for Complex Requirements:
- While Struts 2 offers extensibility, it may not be as flexible as other micro-frameworks when dealing with complex requirements or highly specific use cases.
- Developers may find themselves constrained by the framework’s opinions and predefined patterns.
Less Active Development Compared to Alternatives:
- As the Java web development landscape has evolved, alternative frameworks such as Spring MVC and JavaServer Faces (JSF) have gained significant popularity.
- These frameworks benefit from more active development and larger communities, potentially offering faster updates and a broader range of features.
Poor Documentation:
- Compared to the JSP APIs and standard servlet, Struts has a few numbers of online resources, and many first-time users show the online Apache documentation is confusing and poorly organized.
Less Transparent:
- There are numerous things that are going on behind the scenes rather than normal Java-based Web applications which is a very difficult task to understand the framework.
Struts 2 is a powerful framework that provides a solid foundation for building Java web applications. Its adherence to the MVC pattern, convention over configuration approach, and extensive feature set make it a preferred choice for many developers. However, like any framework, Struts 2 has its own set of advantages and disadvantages. Developers must carefully evaluate their project requirements, and consider the learning curve, configuration complexity, and community support before deciding whether Struts 2 is the right choice for their specific needs. With proper planning and understanding, Struts 2 can empower developers to build robust and scalable web applications that meet the demands of modern businesses.
Why is Struts 2 so Popular?
Struts have gained popularity for several reasons:
- Established Framework: Struts has been around for many years and has a solid reputation as a reliable and stable framework. It has been extensively used in the industry and has proven its effectiveness in developing Java web applications.
- Mature and Stable: Struts is a mature framework with a stable codebase. It has undergone years of development, bug fixes, and improvements, making it a reliable choice for building web applications. Its stability gives developers confidence in using the framework.
- MVC Architecture: Struts follows the Model-View-Controller (MVC) architectural pattern, which provides a clear separation of concerns. This separation makes the code more maintainable, reusable, and easier to understand. Developers appreciate the organization and structure that the MVC pattern brings to their projects.
- Extensive Documentation and Resources: Struts has a wealth of documentation and resources available, including tutorials, guides, and community support. This extensive support makes it easier for developers to learn the framework, troubleshoot issues, and find solutions to common problems.
- Convention over Configuration: Struts embraces the convention over configuration principle, reducing the need for explicit configuration files. By following naming conventions and predefined patterns, developers can save time and effort in configuration, resulting in faster development cycles.
- Integration Capabilities: Struts integrates well with other popular Java technologies and frameworks such as Hibernate, Spring, and Tiles. This integration allows developers to leverage existing tools, libraries, and frameworks, making it easier to build robust and feature-rich applications.
- Validation Framework: Struts provides a powerful validation framework that simplifies form validation. It offers a wide range of validation rules, and error handling mechanisms, and supports both server-side and client-side validation. This built-in validation capability saves developers time and effort in implementing data validation.
- Wide Adoption: Struts has been widely adopted in the industry, and many organizations have built successful applications using the framework. This widespread usage has resulted in a large community of developers, which leads to better community support, resources, and knowledge sharing.
- Enterprise-Ready Features: Struts was designed with enterprise-level applications in mind. It provides features such as security, internationalization support, error handling, and logging out of the box. These features are essential for building robust and secure applications for businesses.
- Compatibility with Existing Struts 1 Applications: Struts 2 was designed to be backward compatible with Struts 1 applications. This compatibility allows organizations with existing Struts 1 applications to migrate to Struts 2 gradually, without the need for a complete rewrite.
Struts 2 based on MVC Architecture
Struts 2 is based on the Model-View-Controller (MVC) architectural pattern, which provides a structured approach to developing web applications. The framework follows the principles of MVC by separating the application into three interconnected components: the Model, the View, and the Controller.
Model
- In Struts 2, the Model represents the application’s data and business logic.
- It encapsulates data-related operations, such as data retrieval, storage, validation, and manipulation.
- The Model component is typically implemented using Plain Old Java Objects (POJOs), which are responsible for interacting with databases, services, or other data sources.
- The Model holds the application’s state and is independent of the View and the Controller.
View
- The View in Struts 2 is responsible for presenting the user interface and displaying the data to the users.
- It receives input from users and communicates with the Controller to update the Model as necessary.
- In Struts 2, the View is typically implemented using JavaServer Pages (JSP) or other templating technologies.
- The View is passive and focuses solely on the presentation layer, rendering the Model data to the users.
Controller
- The Controller in Struts 2 acts as an intermediary between the Model and the View.
- It receives user input from the View and translates it into actions to update the Model and/or the View.
- The Controller component is responsible for managing the flow of data between the Model and the View.
- In Struts 2, the Controller is implemented using Action classes.
- These classes handle user requests, interact with the Model, and determine the appropriate View to display the results.
The flow of control in Struts 2 follows the MVC pattern:
- The user interacts with the View, such as by submitting a form or clicking a button.
- The View sends the user’s input to the Controller (Action classes) through HTTP requests.
- The Controller receives the user’s input and processes it, interacting with the Model as necessary to update the application’s data.
- The Controller determines the appropriate View based on the action’s outcome and prepares the data to be displayed.
- The Controller communicates with the View, passing the data required for rendering.
- The View receives the data from the Controller and displays it to the users, typically using JSP or other templating technologies.
- The cycle continues as users interact with the View, and the Controller handles subsequent requests, updating the Model and refreshing the View accordingly.
By separating the application into Model, View, and Controller components, Struts 2 promotes code modularity, reusability, and separation of concerns. This allows for easier maintenance, scalability, and testability of the application. Developers can focus on specific aspects of the application’s functionality without worrying about the intricacies of other components, resulting in more organized and maintainable code.
Struts 1 vs Struts 2
Struts 1 and Struts 2 are both Java web application frameworks that aim to simplify the development of web applications using the Model-View-Controller (MVC) architectural pattern. However, there are significant differences between the two versions. Let’s compare and contrast Struts 1 and Struts 2 across various aspects:
Architecture:
- Struts 1: It follows a monolithic architecture where the ActionServlet acts as a controller and the ActionForm encapsulates the model and form data. The framework relies heavily on servlets and JSPs for request handling and view rendering.
- Struts 2: It adopts a more flexible and modular architecture. The framework introduces the concept of Interceptors, which allow for cross-cutting concerns and provides cleaner separation of the model, view, and controller. Struts 2 leverages OGNL (Object-Graph Navigation Language) for data binding and expression evaluation.
Convention Over Configuration:
- Struts 1: It requires explicit configuration using XML files for defining the mappings between requests, actions, and views. Developers need to provide detailed configurations for each component and action mapping.
- Struts 2: It embraces convention over configuration, reducing the need for explicit configuration. Developers can follow naming conventions and predefined patterns to minimize configuration efforts. It provides sensible defaults and auto-wiring of components, simplifying the development process.
Validation Framework:
- Struts 1: It provides basic validation capabilities through the ActionForm and supports server-side validation using validation methods. It lacks built-in client-side validation.
- Struts 2: It offers a robust and extensible validation framework. Struts 2 supports both server-side and client-side validation, making it easier to implement and maintain form validations. It includes a wide range of pre-built validation rules and error-handling mechanisms.
Tag Libraries:
- Struts 1: It provides its own custom tag library (Struts Tags) for creating dynamic web pages and interacting with forms and actions.
- Struts 2: It supports multiple tag libraries, including Struts Tags (compatible with Struts 1) and the more powerful and flexible UI tag library (Struts UI Tags). The UI tag library simplifies the creation of user interfaces with rich and interactive components.
Ajax Support:
- Struts 1: It has limited built-in support for Ajax. Developers need to rely on additional JavaScript frameworks or plugins for implementing Ajax functionality.
- Struts 2: It offers enhanced built-in support for Ajax through its integration with the Dojo Toolkit. Struts 2 provides Ajax tags and Interceptors, making it easier to develop Ajax-enabled applications without relying heavily on external libraries.
Testability:
- Struts 1: It can be challenging to test Struts 1 applications due to tight coupling with servlets and other components. Unit testing requires frameworks like StrutsTestCase to simulate container environments.
- Struts 2: It has improved testability due to its modular and loosely coupled architecture. Struts 2 actions can be easily tested using popular testing frameworks like JUnit or Mockito, without the need for a container.
Community Support:
- Struts 1: It has a large and well-established community with extensive resources, documentation, and third-party libraries available. However, the community’s focus has shifted more towards Struts 2 in recent years.
- Struts 2: It has an active and growing community with regular updates, improvements, and new features. The community actively provides support, resources, and plugins for developers.
Threading Model:
- Struts 1: Actions must be thread-safe because all the requests for that Action are handled by only one instance of a class so Struts 1 Actions are singletons. The singleton strategy binds to Struts 1 Actions and provides more care to make the action resources synchronized or thread-safe while developing an application.
- Struts 2: It doesn’t have thread-safety issues because each request is instantiated by an Action object. A servlet container provides many throw-away objects per request
Expression Language:
- Struts 1: Struts1 is integrated with JSTL, hence it uses the JSTL EL. The EL has a relatively weak collection but has basic object graph traversal.
- Struts 2: Struts 2 uses JSTL, but the framework suggests a more flexible expression language known as Object Graph Notation Language (OGNL).
Control of Action Execution:
- Struts 1: Each module in Struts 1 has separate Request Processors (lifecycles), while all the Actions in the module must share the same lifecycle.
- Struts 2: Different lifecycles are created on an Action basis via Interceptor Stacks. Custom stacks are created and used with different Actions, as required.
It’s important to note that Struts 2 is not a direct upgrade or evolution of Struts 1 but rather a reimagining and rewriting of the framework. Struts 2 addresses many limitations and complexities of Struts 1 and offers a more modern and flexible approach to building Java web applications.
In the next article, I am going to discuss Model 1 and Model 2 Architecture in detail. Here, in this article, I try to give a brief introduction to Java Struts Framework and I hope you enjoy this Introduction to Java Struts Framework article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.