Browse by Domains

Introduction to Struts in Java

Struts in Java is an open-source framework that is made by Apache. Apache provides a free source to download Struts for users. It follows the MVC (Model View Controller) pattern. There are three models in MVC – Model0, Model1, Model2.

It provides an implementation of MVC architecture. It gives us pre-built classes for MVC that we can use/extend. Struts have their custom tag libraries. If you are not a java developer, you can not implement Struts applications.

Struts in Java are used to develop web applications which are usually based on servlet and JSP. It simplifies the development and maintenance of web applications by providing predefined functionality. It is based on a front controller, which means it has a controller in front of it which decides on which model request has to come or go. Struts in Java are very helpful for us as MVC is a guideline followed by all technologies in today’s world. There is no better option to simplify web applications other than MVC. Struts are not distributed.

There are two versions of struts-

  1. 1.x(1.0,1.1,1.2)
  2. 2.x(2.0,2.1,2.2)

The first version of struts is rarely used by companies. Most companies prefer the second version of it. The second version of struts includes additional features. In struts 1.x uses servlet based controllers, but in struts 2.x, uses filter based controllers.

Struts 1.x

  • Server side validation
  • i18N
  • Form backup Support
  • Exception Handling
  • Modularization
  • Multi button
  • Tiles Support
  • Plug-in support

Struts 2.x

It is a brand new framework by Apache software foundation. The following facilities are available in struts 2.x-

  • Filter based controller
  • It uses both XML files and annotations for configuration.
  • It also supports zero configuration web application.
  • It also implements AOP(Aspect Oriented Programming) for cross-cutting tasks with the help of interceptors.

Cross-Cutting task–> A task which applies again and again. For example- logging is used by admin. Logging is the way by which we can provide authentication. This is a technique in which the application is not directly used.

We use Interceptor for using this logic. Interceptor is just a java class.

  • It also does the concept of DI.
  • It has inbuilt support for file uploading, validations, Ajax etc.
  • It also provides a custom tag library to develop views etc.

We can also develop web applications by servlet and JSP, but we have to perform a lot of coding for implementing MVC. And this is the major task for a user to do. In today’s world, everyone wants to do a task easily. So struts 2 customizes the task.

Components of Struts in Java

There are many components of struts. They are as follows-

  1. Filter Dispatcher
  2. Action
  3. Result
  4. Configuration file
  5. Interceptors
  6. Deployment descriptor
  7. Tag Library

The user has to know all the components of Struts to use Struts applications. Otherwise, there is no possibility to develop applications without knowing these components.

1. Filter Dispatcher

It is the controller component of Struts application. From a coding point of view, the controller is represented by org.Apache.Struts2.filtered patcher class, which is just a filter class.

A controller component is responsible for each incoming request and identifies appropriate actions to process the request at outer processing. The request is also responsible for identifying appropriate views to display the result with the help of the result component.

Note: Struts 2 says when a request comes from the login page then it will not go to the direct JSP page, and it comes from the controller.

<form action= “bean.jsp”>

Here, action refers to the information the user holds by this. In other words, this is a java bean class.

2. Action

In Struts 2, the functionality of the model is represented by the action component. From a coding point of view, an action is represented by a bean class containing the state of an application and any business logic. This component is developed by the programmer. An Action is a model in Struts 2 which is used to handle all the data.

3. Result

The result means view. In the Struts2 application, the functionality of view is managed by the result component. That is, the result component is responsible for the presentation logic of the Struts application.

A result is responsible for identifying JSP pages to display the results.

4. Configuration file

Struts 2 uses a configuration file to describe the action, result and other resources. The name of this file is — struts.xml.

5. Interceptors

Interceptors are the helper components of the controller and are responsible for applying cross-cutting concerns or other commonly used logics. Wherever we want to use the logic in JSP or servlet, we use interceptors. There are many interceptors in Struts.

6. Deployment Descriptor

This is the deployment descriptor of the Struts Application and contains the information about controller web.xml. All information gathered in the deployment descriptor, which is used in MVC. It stores information about how many JSP and servlets used in this application. Basically, it is the XML file.

7. Tag Library

Struts 2 provides a custom tag library to develop JSP pages and to manipulate the data. The user can design the form or text using the tag library. First, we make the tag directive in this library.

Structure of Struts.XML file

Struts is the root element of these files. Packages are the sub element of Struts that defines the set of actions and results.

<struts>
   <constant name = "struts.devMode" value = "true" />
   <package name = "helloworld" extends = "struts-default">
     
      <action name = "hello" 
         class = "hello.struts2.HelloWorldAction" 
         method = "execute">
         <result name = "success">/HelloWorld.jsp</result>
      </action>
      
      <-- more actions can be listed here -->
 
   </package>
   <-- more packages can be listed here -->
</struts>

Commonly used Tags of Struts Library

<S: form> : It is similar to a HTML tag. It is used to create Struts based HTML forms.

Syntax:

<S: form name = “name & action”>
Sub element of form
</S: form>


Sub elements:

<S: submit>: Submit button is created using this element.

<S: text>: It is used to create a text field.

<S: textarea>: A text area is created using this element.

There are some automatic features of Struts 2:

  • Param transfer to member variables.
  • Validation
  • It is easy to learn as it is very simple.
  • It provides good tag libraries.
  • It supports many convenient features.
  • It is extensible.
  • It is also flexible.
  • It is very well integrated with J2EE.

Implementation

View Part

  1. Form Tag Support
  •    Validation/ form backup
  1. I18N Tag Support
  2. Logical Tag Support
  3. Tiles Tag Support

Controller Part

  1. Multi action class
  2. Multi button support
  3. Multi form controller
  4. Exception handler
  5. Plug-in Support
  6. Pre handler Support

Working of Struts

IMG_256

In the initialization phase, the controller rectifies a configuration file and uses it to deploy other control layer objects. Struts in Java configuration is formed by these objects combined. The struts configuration defines, among other things, the action mappings for an application.

Struts controller servlet considers the action mappings and routes the HTTP requests to other components in the framework. The request is first delivered to an action and then to JSP. The mapping helps the controller to change HTTP requests into application actions. The action objects can handle the request form and respond to the client (generally a web browser). Action objects have access to the applications controller servlet and also access to the servlet’s methods. When delivering the control, an action object can indirectly forward one or more shared objects, including JavaBeans, by establishing them in the typical situation shared by java servlets.

Design Patterns

  • Front Controller Pattern
  • Command Pattern
  • Composite Pattern
  • Decorator Pattern

Advantages of Struts

  • An advanced framework with a lot of features.
  • Based on the MVC architecture.
  • Simple configuration.
  • Interceptors to reduce the cross cutting functionality.
  • OGNL
  • Pluggable with different Result types like Ajax, JSP, Free Marker, Velocity etc.

Importance of Frameworks

  • Automates all tedious tasks of application.
  • Introduces an elegant architectural solution.
  • Uses the design patterns commonly agreed and that are standard in the industry.
  • Gives a lot of features that are commonly needed by most of the projects.

Why is Struts so useful?

  1. Structural separation of data presentation and business logic
  •   Easy separation of development tasks(web design, database…)
  •   Increases maintainability and extensibility(new views!)
  •   Increases reusability of code
  1. Struts provides a controller that manages the control flow
  •  Changes in the flow can all be done in struts-config.xml
  •  Abstraction from (hard coded) filenames (forwards)
  1. Easy localization ( internationalization is more important than ever)
  2. Based on standard Java technologies ( JSP, Servlets, Javabeans)
  •  Thus running on all kinds of JSP/ Servlet containers
  1. Open-source
  •  Affordable
  • No dependence on external companies
  • Robustness ( due to freely accessible source code)
  1. Very vivid open-source project with growing developer community.

Interceptors

In Struts 2, an interceptor is a type of object which is invoked at the preprocessing and postprocessing of a request. 

Interceptors perform various operations in Struts2, which are as follows-

Displaying intermediate result, validation, internationalization and exception handling.

In interceptors, the user has to remove the entry from the struts.xml file. If the user wants to remove validation, exception handling or any other concern from any applications, then the user does not need to adjust the application.

Struts 2 provides many interceptors and the users have a choice to create their own interceptors. So these are-

  1. Cookie
  2. Checkbox
  3. Chain
  4. Debugging
  5. Alias
  6. execAndWait
  7. fileUpload
  8. I18n
  9. Store
  10. Exception
  11. Logger
  12. conversionError
  13. Prepare
  14. Scope
  15. jsonValidation

Dispatch Action

Dispatch action is a concept that is used to implement the concept of multiple method definitions inside the action. It means dispatch action provides the facilities to execute a method among the multiple methods of the same action to process the request. Generally, dispatch action is used if the action class contains logically related functionalities.

There are two ways to implement dispatch action:

  1. Static method invocation
  2. Dynamic method invocation

Steps to create Dispatch Action

  1. In a jsp file first create the multiple buttons having their own action.
  2. In the action class define the method for each operation but the signature of these methods must be the same as the execute method.

Note: The name of these methods must be given according to their action in the JSP file.

Value Stack

  1. It’s not really a stack in the traditional sense.
  2. It does stack up objects.
  3. Behaves like a virtual object.
  4. Makes it easy to refer to member variables.

Suppose 10 clients work at the same time for a particular action, then 10 objects are created in the value stack. This is because it is a single thread for every 10 threads. It is not multi-threading.

OGNL

OGNL is an object graph navigation language. It helps in type conversion and expression language. It is more powerful as it can also invoke methods in java using expression language. 

OGNL has form tags to generate the form and to point the bean and field in which the values have to be set. It also has UI tags to display the results from various types like arrays, collections etc. OGNL also takes care of the type conversion to set the form values to the beans ( from primitive or custom types to string).

Note:

  1. Object Graph Navigation Language is an expression language to access the objects referred by the value stack.
  2. Value stack is from the Struts 2 framework.

This brings us to the end of the blog on Struts in Java. We hope that you were able to grasp the concept well. If you wish to learn more such concepts, join Great Learning Academy’s Free Online Java Programming Courses and upskill today!

Engaging in the study of Java programming suggests a keen interest in the realm of software development. For those embarking upon this journey with aspirations towards a career in this field, it is recommended to explore the following pages in order to acquire a comprehensive understanding of the development career path:

Software engineering courses certificates
Software engineering courses placements
Software engineering courses syllabus
Software engineering courses fees
Software engineering courses eligibility
Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top