Apache Struts is a popular open-source framework for developing web applications in Java. It follows the Model-View-Controller (MVC) architecture pattern, which helps separate the logic, presentation, and data layers of an application, making it easier to manage, scale, and maintain.
Struts is designed to provide a consistent way to develop web applications in Java, enabling developers to focus on building business logic and user interfaces without having to deal with the intricacies of low-level infrastructure. Initially introduced in 2000 and widely adopted for enterprise-level applications, Struts has evolved to become an essential tool in the Java EE ecosystem.
1. Core Features of Apache Struts
Model-View-Controller (MVC) Architecture
Struts implements the MVC design pattern:
- Model: Represents the application data and business logic. It could be a simple POJO (Plain Old Java Object) or a more complex enterprise bean.
- View: Responsible for displaying the data to the user, typically using JSP (JavaServer Pages), HTML, or Freemarker templates.
- Controller: Coordinates the user request, invokes the model for business logic, and forwards the results to the appropriate view. Struts uses a centralized controller called the ActionServlet.
Action Class
The Action class in Struts acts as a controller in the MVC pattern. Each request from the client is mapped to an Action class. It processes user input, interacts with the model (business logic), and forwards the result to the appropriate view.
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
// Business logic (e.g., validate login credentials)
return mapping.findForward("success");
}
}
ActionMapping
: Maps the request to an Action.ActionForm
: Holds the form data for processing.ActionForward
: Determines the next page or view.
Struts Config File
Struts uses an XML configuration file, typically called struts-config.xml
, to map incoming requests to corresponding Action classes and views.
<action-mappings>
<action path="/login" type="com.example.LoginAction" name="loginForm" scope="request" input="/login.jsp">
<forward name="success" path="/welcome.jsp"/>
<forward name="failure" path="/loginError.jsp"/>
</action>
</action-mappings>
In this example:
- The request
/login
is handled byLoginAction
. - If successful, the user is forwarded to
/welcome.jsp
. - If unsuccessful, the user is forwarded to
/loginError.jsp
.
2. ActionForm (Data Transfer Object)
ActionForm is a JavaBean used to store data submitted by the user in the view (e.g., an HTML form). It is often used for form validation and data transfer between the view and the action class.
Example of an ActionForm:
public class LoginForm extends ActionForm {
private String username;
private String password;
// Getters and setters
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
- Struts automatically populates the properties of the ActionForm from the submitted form.
- Form data is available for validation and processing in the Action class.
3. Struts Tags and Tag Libraries
Struts provides a set of custom tags to simplify the development of JSP pages. These tags can be used to interact with the ActionForm and other Struts components. Some common tags include:
HTML Tags
<html:form>
: Creates a form tag.<html:text>
: Renders a text input field.<html:submit>
: Renders a submit button.
Example of a form in a JSP:
<html:form action="/login">
<html:text property="username"/>
<html:text property="password" type="password"/>
<html:submit value="Login"/>
</html:form>
- The
property
attribute of the tags is bound to the corresponding property of theActionForm
(in this case,username
andpassword
).
Logic Tags
Struts also provides logic tags to control the flow of the page (e.g., conditionally displaying content).
Example:
<logic:present property="username">
Welcome, <bean:write name="loginForm" property="username"/>
</logic:present>
This tag checks if the username
property of the loginForm
is present and displays a personalized welcome message.
4. Interceptors (Struts 2)
In Struts 2 (an evolved version of Struts 1.x), Interceptors provide a way to intercept and manipulate the request-response cycle before or after an action is executed. They are used to handle cross-cutting concerns such as:
- Logging
- Authentication/Authorization
- Input validation
- Exception handling
Example of an Interceptor in Struts 2 configuration:
<interceptors>
<interceptor name="loggingInterceptor" class="com.example.LoggingInterceptor"/>
</interceptors>
Interceptors are defined in the struts.xml configuration file.
5. Struts Validation Framework
Struts provides a Validation Framework that allows developers to validate user input in a centralized way. The validation configuration can be defined in XML (validation.xml
) or through annotations in Struts 2.
Example of validation in Struts 1.x:
<form-bean name="loginForm" type="com.example.LoginForm">
<form-field name="username" type="string" required="true" maxlength="30"/>
<form-field name="password" type="string" required="true" maxlength="15"/>
</form-bean>
Struts will automatically validate the fields based on these rules when the form is submitted.
6. Struts Workflow
The general workflow in a Struts-based application is:
- Client Request: The user submits a request (e.g., a form submission or URL request).
- ActionServlet: The
ActionServlet
processes the request and delegates it to the appropriateAction
class based on configuration (struts-config.xml
). - Action Class: The
Action
class processes the request and performs the necessary business logic. It can forward the result to a view (JSP). - View (JSP): The view renders the response to the user.
7. Advantages of Using Apache Struts
- MVC Pattern: Struts simplifies the development by providing a clear separation between the presentation, business logic, and data layers.
- Extensibility: Struts can be easily extended to add new functionalities, such as custom tags, interceptors, and plugins.
- Validation: Built-in validation mechanisms help to reduce the complexity of managing user input.
- Support for Internationalization: Struts provides support for internationalization and localization, enabling the development of multi-lingual applications.
- Easy Integration: Struts integrates well with other Java technologies such as Spring, Hibernate, and JDBC.