Struts 2 Components
In this article, I am going to discuss Java Struts 2 Components. Please read our previous article where we discussed Model 1 and Model 2 (MVC) Architecture. At the end of this article, you will understand the following pointers in detail which are related to Java Struts 2 Components.
- Action Beans
- Action servlets
- ActionForm beans and Custom Tags
- Value Stack / OGNL
- Results / Result types
- View Technologies
- Action context
Let us understand the need and use of the above struts 2 components one by one in detail.
What is the Bean tag?
- It is used to create an instance of a bean in a JSP page.
- It is a combination of the set and push tags.
- The bean should have a no-argument constructor.
In Struts 2, Action Beans are Java classes that play a crucial role in the framework’s architecture. They act as the central point of communication between the user’s interactions, the application’s business logic, and the presentation layer. Action Beans are responsible for handling user requests, processing input data, and coordinating the flow of data between the Model and the View. Here are the key characteristics and responsibilities of Action Beans in Struts 2:
- Implementation of Actions: Action Beans implement the Action interface or extend the ActionSupport class provided by the Struts 2 framework. These classes define the behavior and actions that the application can perform in response to user requests.
- Mapping to URLs: Action Beans are associated with specific URLs through configuration. When a user makes a request to a particular URL, the corresponding Action Bean is invoked to handle that request. This mapping is typically defined in the framework’s configuration files, such as the struts.xml file.
- Method Invocation: Action Beans handle user requests by invoking specific methods based on the type of request received. These methods are commonly referred to as action methods or action handler methods. The framework uses reflection to invoke the appropriate method based on the request parameters and configuration.
- Access to Request Data: Action Beans have access to the request parameters and data submitted by the user. They can retrieve data from HTTP request parameters, query strings, or form submissions and perform any necessary data processing or validation.
- Interaction with the Model: Action Beans facilitate the interaction between the View and the Model components of the MVC pattern. They can retrieve data from the Model, modify the Model’s state, and store data for use by the View during rendering. This interaction is typically achieved through services, data access objects (DAOs), or other components responsible for data management.
- Result Handling: After processing a user request, Action Beans return a result to the framework, which determines the next step in the application flow. The result can be a view template (such as a JSP or FreeMarker template), a redirect to another URL, or any other valid result type defined in the configuration.
- Scope Management: Action Beans manage the scope of their data. They can store data in instance variables, request attributes, or session attributes depending on the desired scope and lifespan of the data. Struts 2 provides several built-in scopes, including request, session, and application scopes, allowing developers to manage data persistence as needed.
Overall, Action Beans in Struts 2 serve as the primary entry point for handling user requests and orchestrating the flow of data within the framework. They encapsulate the business logic related to user interactions, process input data, and interact with the Model and the View to provide the appropriate response. Action Beans are configurable entities that allow developers to define the behavior and customization of their application’s actions within the Struts 2 framework.
In Struts 2, there is no specific concept of “Action Servlets” as in Struts 1. Unlike Struts 1, Struts 2 does not use a single servlet (ActionServlet) to handle all requests. Instead, it utilizes a front controller pattern and various filters to handle requests and delegate them to appropriate components.
In Struts 2, the central component responsible for request handling is the org.apache.struts2.dispatcher.FilterDispatcher, which is a filter provided by the framework. This filter intercepts incoming requests and acts as a front controller, routing the requests to the appropriate components based on the requested URL. Here’s an overview of how request handling works in Struts 2:
- Front Controller: When a request is received by the web server, it passes through the FilterDispatcher filter. This filter intercepts the request and acts as a central hub for request processing in Struts 2.
- Configuration: The FilterDispatcher consults the framework’s configuration files, such as struts.xml, to determine the appropriate configuration for the incoming request. These configuration files define mappings between URLs and the corresponding action classes, result types, and other configuration elements.
- Action Invocation: Based on the configuration, the FilterDispatcher identifies the appropriate action class associated with the requested URL. It creates an instance of the action class and populates it with the request parameters and other data.
- Action Execution: The FilterDispatcher invokes the appropriate methods of the action class, typically using the execute() method, to perform the desired business logic and process the request. The action class may interact with the model, perform data manipulation, and prepare data for the view.
- Result Handling: Once the action execution is complete, the FilterDispatcher determines the appropriate result type based on the action’s configuration. This could be a view template (such as a JSP or FreeMarker template), a redirect to another URL, or any other valid result type.
- View Rendering: The FilterDispatcher delegates the rendering of the response to the result type handler associated with the selected result type. The result type handler prepares the data and forwards it to the appropriate view template for rendering.
- Response: Finally, the rendered view is returned as the response to the original request, completing the request processing cycle.
It’s important to note that while Struts 2 does not have a concept of “Action Servlets” like Struts 1, it employs a combination of filters, interceptors, and configuration files to achieve the same request handling and processing functionality in a more flexible and modular manner. Action servlets can be described using the following diagram:
Action Form Beans
In Struts 2, Action Form Beans, also known as Action Forms or simply Forms, are Java classes that serve as a data transfer object between the View and the Controller components. They encapsulate the form data submitted by the user and provide a way to validate and bind the form data to the corresponding properties of the Action Beans. Here are the key characteristics and responsibilities of Action Form Beans in Struts 2:
- Data Binding: Action Form Beans facilitate the binding of form data submitted by the user to the corresponding properties of the Action Beans. They provide a mechanism to capture user input and transfer it to the appropriate fields of the associated Action Bean.
- Property Validation: Action Form Beans often include validation rules to ensure the correctness and integrity of the form data. They define validation constraints, such as required fields, length limits, data formats, and custom validation rules. The validation is typically performed during the form submission process.
- Populating Form Data: Action Form Beans can prepopulate form fields with initial values. This feature is useful for displaying preexisting data to users, such as editing forms or prefilling data based on a user’s previous selections.
- Mapping to Views: Action Form Beans are associated with specific views or form templates in the configuration. This association is typically defined in the framework’s configuration files, such as struts.xml, using the <action> configuration element.
- Scope Management: Action Form Beans manage the scope of their data. They can store form data in instance variables, request attributes, or session attributes depending on the desired scope and lifespan of the data. Struts 2 provides several built-in scopes, including request, session, and application scopes, allowing developers to manage data persistence as needed.
- Data Conversion and Formatting: Action Form Beans can handle data conversion and formatting to match the expected types of the associated Action Beans. For example, they can convert input strings to numeric values or dates, allowing for consistent and reliable data representation.
- Error Handling: Action Form Beans are responsible for capturing and reporting validation errors. If any validation errors occur during the form submission process, the errors are typically associated with the corresponding form fields and made available for display in the View.
By utilizing Action Form Beans, Struts 2 provides a way to handle form data, perform validation, and transfer the data to the appropriate Action Beans. This separation of form data and business logic promotes cleaner code organization and enhances the maintainability and reusability of the application. Action Form Beans play a crucial role in the Model-View-Controller (MVC) architecture of Struts 2 by facilitating the communication between the View and the Controller components while managing form data and validation.
In Struts 2, custom tags are a feature that allows developers to create their own custom JSP tags to enhance the functionality and ease of use in the presentation layer of a web application. Custom tags provide a way to encapsulate reusable UI components or logic and make them available for use on JSP pages. Here are the key aspects and benefits of using custom tags in Struts 2:
- Reusability: Custom tags enable developers to encapsulate reusable UI components or logic into a single tag. By defining custom tags, developers can easily reuse these components across multiple JSP pages, promoting code reusability and reducing duplication.
- Abstraction of Complex Logic: Custom tags provide a mechanism to encapsulate complex presentation logic or calculations. Developers can abstract away the details of the implementation and provide a simpler interface for interacting with the custom tag. This abstraction makes the JSP pages cleaner and easier to understand.
- Separation of Concerns: Custom tags promote the separation of concerns between the presentation layer and the underlying business logic. By encapsulating complex or specific UI behaviors within custom tags, developers can keep the JSP pages focused on rendering and displaying data while moving the logic into reusable tags.
- Improved Readability and Maintainability: Custom tags enhance the readability and maintainability of JSP pages. By replacing complex Java code snippets with custom tags, the JSP pages become more concise and easier to read. This abstraction also allows for better maintainability as changes to the custom tag implementation can be made in a single location.
- Enhanced Productivity: Custom tags provide a higher level of abstraction and simplify the development process. Developers can create reusable UI components with custom tags, reducing the need to write repetitive code and accelerating the development of the application.
In the context of Struts 2, the framework provides its own set of custom tags known as Struts Tags. These tags cover various common use cases in web application development, such as form fields, validation, iteration, control flow, and internationalization. Struts Tags provide an additional layer of abstraction, making it easier to work with form data, handle user input, and interact with Struts 2 components.
Furthermore, developers have the flexibility to create their own custom tags specific to their application’s requirements. This can be achieved by extending the existing Struts Tags or creating entirely new custom tags using JSP Tag Library Descriptor (TLD) files.
Overall, custom tags in Struts 2 allow developers to encapsulate reusable UI components, abstract complex logic, promote separation of concerns, and improve productivity. They provide a powerful mechanism for enhancing the presentation layer of web applications and creating more maintainable and reusable code.
Why do we use Custom tags?
- Eliminating the need for scriptlet tags and the non-existence of any scriptlet tags gives a good coding approach.
- Separation of business logic from JSP isolates business logic from JSP pages, which makes maintenance much easier.
- Re-usability Due to the use of custom tags the same business logic can be used repeatedly.
In Struts 2, interceptors are a key component of the framework that provides a powerful mechanism for intercepting and modifying the behavior of requests and responses in the request processing lifecycle. Interceptors allow developers to implement cross-cutting concerns and perform actions before and after the execution of an action or the rendering of a view. Here are the key aspects and functionalities of interceptors in Struts 2:
- Request Processing Flow: Interceptors are executed at various points in the request processing flow, allowing developers to intercept and modify the behavior of the framework. They are invoked before and after the execution of actions, giving developers the opportunity to perform custom logic, such as authentication, logging, validation, or caching.
- Configurability: Interceptors in Struts 2 are highly configurable. Developers can define the order in which interceptors are executed, specify which actions or URLs are intercepted, and configure various properties and parameters for each interceptor. This configurability allows for fine-grained control over the application’s behavior and facilitates the implementation of specific requirements.
- Preprocessing and Postprocessing: Interceptors provide a way to perform preprocessing and postprocessing actions. Before an action is executed, interceptors can preprocess the request, perform validations, modify parameters, or handle authorization. After the execution of an action, interceptors can post process the response, manipulate the result, or perform any necessary cleanup tasks.
- Chaining Interceptors: Multiple interceptors can be chained together to create a pipeline of processing steps. Each interceptor in the chain can modify the request, invoke the next interceptor, and process the response from the previous interceptor. This chaining mechanism allows for modularization and the composition of cross-cutting concerns.
- Interceptor Stacks: Interceptors can be grouped into stacks, which define a predefined sequence of interceptors that are commonly used together. Struts 2 provides built-in interceptor stacks, such as the default stack, which includes interceptors for common tasks like parameter parsing, validation, and result handling. Developers can also create custom stacks to encapsulate specific sets of interceptors for reuse across multiple actions.
- Custom Interceptors: Struts 2 allows developers to create custom interceptors to implement application-specific behavior. By extending the framework’s interceptor classes or implementing the Interceptor interface, developers can define their own interceptors tailored to their application’s requirements. Custom interceptors can be used to implement features like auditing, performance monitoring, encryption, or any other custom cross-cutting concern.
Interceptors in Struts 2 provide a powerful mechanism for implementing cross-cutting concerns and customizing the behavior of the framework. They allow developers to add functionality, modify requests and responses, and perform preprocessing and postprocessing tasks. With their configurability and the ability to chain multiple interceptors together, developers have fine-grained control over the application’s request processing flow and can easily implement complex functionality without cluttering the main action code.
Why Interceptor is used?
To delete any concern like validation, exception handling, logging, etc. from the application, there is no need for the redeployment of the application, what we need to do is that just eliminate the entry from the struts.xml file
In Struts 2, the Value Stack is a data structure that holds the values of objects used in an action invocation and provides a way to access and manipulate these values within the framework. The Value Stack serves as a bridge between the action classes, the view templates, and other components involved in the request processing flow. Here are the key aspects and functionalities of the Value Stack in Struts 2:
- Data Storage: The Value Stack stores objects and their values that are relevant to the current action invocation. This includes objects such as action classes, models, form beans, and other objects that are pushed onto the stack. The values of these objects can be accessed and manipulated by the view templates and other components involved in the request processing.
- Hierarchical Structure: The Value Stack has a hierarchical structure, where each action invocation has its own stack. The hierarchical structure allows for scoping and organizing data based on the request and action invocation. The stack follows a Last-In-First-Out (LIFO) approach, where newly pushed objects take precedence over the previously pushed objects with the same name.
- OGNL Expression Evaluation: The Value Stack integrates with the Object-Graph Navigation Language (OGNL) expression language. OGNL expressions can be used to access and manipulate the values of objects on the stack. OGNL expressions provide a concise and powerful way to reference properties, invoke methods, and perform dynamic operations on the objects within the stack.
- Accessing Values in Views: In view templates, such as JSP or FreeMarker templates, the Value Stack is accessible via the implicit stack object. The values stored on the stack can be accessed directly using OGNL expressions or through tags provided by the framework, such as Struts Tags or OGNL-based tags. This allows for easy retrieval and rendering of data in the view layer.
- Value Resolution: When a value is requested from the Value Stack, it follows a predefined resolution order. The stack first searches for the value on the topmost object and then continues down the hierarchy until it finds the value or reaches the end of the stack. This resolution order ensures that values are retrieved from the appropriate object on the stack.
- Value Manipulation: The Value Stack allows for the manipulation of values, such as setting new values, updating existing values, or removing values from the stack. This provides flexibility in modifying data during the request processing flow, enabling actions to update values or prepare data for rendering in the view layer.
- Scoped Data: The Value Stack supports scoping of data at different levels. In addition to the top-level scope, which holds the action objects, the stack can have nested scopes for objects related to iterations, subactions, or other components. This scoping capability allows for encapsulation and proper separation of data based on its context and lifespan.
The Value Stack in Struts 2 provides a convenient and powerful mechanism for accessing and manipulating data within the framework. It enables the seamless flow of data between action classes and view templates, allowing for dynamic rendering and interaction. With its hierarchical structure and integration with OGNL expressions, the Value Stack simplifies data management and retrieval, enhancing the overall development experience in Struts 2.
In Struts 2, results refer to the outcomes or responses generated by an action after it has been executed. Results define how the framework should handle the response and what should be rendered to the user. They determine the next step in the request processing flow and play a crucial role in the interaction between the action and the view. Here are the key aspects and functionalities of results in Struts 2:
- Rendering Views: Results specify the view templates or pages that should be rendered to the user. These views can be JSP (JavaServer Pages), FreeMarker templates, Velocity templates, or any other supported view technology. Results define the location and name of the view template to be rendered.
- Result Types: Struts 2 provides a set of built-in result types that cover common use cases, such as rendering JSP pages (dispatcher), redirecting to another URL (redirect), rendering plain text (plainText), or returning JSON data (JSON). Each result type has its own configuration and behavior.
- Custom Result Types: Struts 2 allows developers to define their own custom result types. This enables the customization and extension of the framework’s response-handling capabilities. Custom result types can be used to integrate with third-party libraries, generate custom responses, or handle specialized rendering requirements.
- Result Configuration: Results are configured in the struts.xml file or other configuration files specific to the application. The configuration defines the mapping between the result type and the corresponding view or response. It also specifies any additional parameters or settings required by the result type.
- Result Parameters: Results can accept parameters that provide additional information or customization. For example, a result parameter can specify the name of the JSP page to render, the URL to redirect to, or the content type of the response. Result parameters allow for dynamic behavior and configuration of the response handling.
- Result Stacks: Results can be organized into result stacks, which define a predefined sequence of results that are commonly used together. Result stacks provide a convenient way to encapsulate a set of related results and reuse them across multiple actions. Struts 2 provides built-in result stacks, such as the default stack, which includes commonly used results like dispatcher, redirect, and JSON.
- Multiple Results: Actions in Struts 2 can return multiple results. This allows for conditional or dynamic result selection based on specific conditions or user interactions. The framework evaluates the returned results in order and chooses the first one that matches the current conditions.
Results in Struts 2 define the behavior and response handling after an action has been executed. They specify the view templates to be rendered, the URLs to redirect to, or the data to be returned in the response. By configuring and utilizing results effectively, developers can control the flow of the application and provide the appropriate response to the user based on the action’s outcome.
In Struts 2, view technologies refer to the various technologies or frameworks that can be used to render the user interface and generate the presentation layer of a web application. Struts 2 is designed to be flexible and compatible with different view technologies, allowing developers to choose the one that best suits their needs and preferences. Here are some popular view technologies commonly used with Struts 2:
- JSP (Java Server Pages): JSP is a widely used view technology in Java web development. It allows embedding Java code within HTML markup, providing dynamic content generation and powerful server-side processing capabilities. Struts 2 provides built-in support for rendering JSP pages as view templates.
- FreeMarker: FreeMarker is a template engine that separates the presentation layer from the application logic. It uses template files with a combination of HTML and FreeMarker syntax to generate the output. Struts 2 supports the use of FreeMarker as a view technology, allowing developers to use FreeMarker templates for rendering the user interface.
- Velocity: Velocity is another template engine that follows a similar approach to FreeMarker. It utilizes template files containing a mixture of HTML and Velocity syntax to generate dynamic content. Struts 2 supports Velocity as view technology, enabling developers to utilize Velocity templates for rendering views.
- Thymeleaf: Thymeleaf is a modern server-side Java template engine that promotes clean and natural HTML templates. It provides a powerful and flexible way to render dynamic content by seamlessly integrating with Java code. While not natively integrated with Struts 2, it is possible to use Thymeleaf as a view technology by configuring the necessary components.
It’s important to note that Struts 2 is view technology-agnostic, meaning it does not enforce the use of any specific view technology. Developers have the flexibility to choose the most suitable view technology for their project’s requirements, team expertise, and development preferences. The framework provides support and integration options for various view technologies, allowing developers to leverage their preferred tools and techniques in the presentation layer of their Struts 2 applications.
In Struts 2, the ActionContext class represents the context in which an action is executed. It provides access to various resources and information related to the current action invocation. The ActionContext serves as a container for context-specific data and facilitates communication and coordination between different components involved in the request processing. Here are the key aspects and functionalities of the ActionContext in Struts 2:
- Scope Management: The ActionContext manages the scope of data and objects related to the current action invocation. It provides access to data stored in different scopes, such as request, session, and application scopes. This allows for the retrieval and manipulation of data across different components involved in the request processing.
- Action Parameters: The ActionContext provides access to the action parameters passed in the request. It allows retrieving the parameter values as well as setting and removing parameters dynamically during the request processing.
- Value Stack: The ActionContext holds a reference to the Value Stack associated with the current action invocation. The Value Stack stores the objects and their values used in the action, allowing for access and manipulation of these values within the action and the view templates.
- Session Management: The ActionContext provides access to session-related data and operations. It allows retrieving and storing objects in the session, managing session attributes, and obtaining the session ID associated with the current user session.
- Servlet Context: The ActionContext provides access to the ServletContext, which represents the application-level context in a Java web application. This allows retrieving and setting application-wide attributes, accessing initialization parameters, and performing other operations related to the web application context.
- Locale and Resource Bundles: The ActionContext provides access to the current locale and resource bundles. This allows retrieving the locale information for internationalization purposes and accessing localized messages and resource bundles.
- Thread Safety: The ActionContext is designed to be thread-safe. It ensures that each thread has its own separate instance of the ActionContext to avoid conflicts and ensure the isolation of data across concurrent requests.
The ActionContext serves as a central point of access to the various resources and information related to the current action invocation in Struts 2. It allows for data retrieval and manipulation, scope management, access to the Value Stack, and interaction with session and application-level context. By utilizing ActionContext, developers can effectively access and coordinate the required resources and data during the request processing flow in Struts 2 applications.
In Struts 2, action invocation refers to the process of executing an action in response to a user request. When a user interacts with a web application, such as submitting a form or clicking on a link, the corresponding action is invoked to handle that request and perform the necessary processing. Here are the key aspects and steps involved in the action invocation process in Struts 2:
- Request Routing: When a user makes a request to a specific URL, the Struts 2 framework determines the corresponding action class and method to handle that request. This routing is typically defined in the framework’s configuration files, such as struts.xml, using mappings between URLs and actions.
- Action Object Creation: Once the appropriate action class and method are identified, an instance of the action class is created by the framework. The action class may implement the Action interface or extend the ActionSupport class provided by Struts 2.
- Parameter Population: The framework populates the action instance with the request parameters sent by the user. The parameter values are automatically set on the corresponding properties of the action object, allowing the action to access and process the user’s input.
- Interceptor Execution: Before the action method is invoked, interceptors come into play. Interceptors can perform preprocessing and postprocessing tasks, such as validation, authentication, logging, or data manipulation. Interceptors are configured in the framework’s configuration files and executed in a predefined order.
- Action Method Invocation: After the interceptors have been executed, the appropriate method of the action class is invoked. This method contains the business logic to handle the user’s request. The action method may interact with the model layer, retrieve data, perform calculations, and prepare the data for rendering in the view.
- Result Handling: Once the action method has completed its execution, the framework determines the appropriate result to be generated. The result defines what should be rendered to the user or what further action should be taken. The result can be a view template (such as a JSP page), a redirect to another URL, a JSON response, or any other valid result type configured in the application.
- Rendering and Response: The framework handles the rendering of the result and generates the appropriate response. For view templates, the data prepared by the action method is passed to the template for rendering. The rendered output is then sent back to the user’s browser as a response to the original request.
The action invocation process in Struts 2 involves routing the request to the appropriate action, creating an instance of the action class, populating parameters, executing interceptors, invoking the action method, handling the result, and generating the response. This process ensures that the user’s request is processed in a controlled and customizable manner, allowing for the execution of business logic and the generation of appropriate responses.
In the next article, I am going to discuss Struts 2 Architecture and Flow in detail. Here, in this article, I try to explain Java Struts 2 Components and I hope you enjoy this Java Struts 2 Components 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.