Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Interceptors
2.1.
Default Interceptors
3.
Example
4.
Advantages
5.
Frequently asked questions
5.1.
What is Struts Framework? and its Components?
5.2.
Why do we use Struts?
5.3.
What are some of the new features of Struts2?
5.4.
What do you mean by Interceptors?
5.5.
What is the function of the Struts.xml File in Struts?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Interceptors

Author Ankit Kumar
0 upvote

Introduction

One of the biggest scams in computer programming is trying to understand the concepts by looking at their literal meaning. Here, the case is not at all different from others. Eventually, the literal meaning of the term interceptors has got nothing to do with its importance in the field of computer science, or more specifically, struts.

Introductory image

Let us learn more about it in the subsequent sections.

Interceptors

Interceptors are nothing more than an object that is created at the time of pre-processing or the post-processing of a request. In Struts 2, the interceptor is used to perform operations such as validation, exception handling, internationalization, displaying intermediate results etc.

Demo

There are many interceptors provided by the struts 2 frameworks. We have the option to create our interceptors. The struts 2 default interceptors are as follows:

Default Interceptors

S.No Default interceptors                                                        Description
1 Alias It permits the use of various name aliases for parameters across requests.
2 Checkbox It adds a parameter value of false for check boxes that are not checked to help manage checkboxes.
3 ConversionError It inserts error data from string to parameter type conversion into the action's errors field.
4 CreateSession If no HTTP session is present, one is automatically created.
5 Debugging gives the developer a variety of debugging windows.
6 Timer reveals basic profiling data in the form of the execution time of an action.
7 ExecAndWait It sends the user to a waiting page in between the action being completed in the background.
8 ServletConfig
 
gives the action access to a variety of servlet-based data.
9 Profile enables the logging of basic profiling data for actions.
10 Validation It provides support to input validation.
11 Token The action is checked for a valid token to avoid multiple form submissions
12  Scope the status of the action is saved and retrieved in the session or application scope.
13 Prepare Usually, this is used for pre-processing tasks like setting up database connections.
14 Exception enables automatic exception handling through redirection by mapping exceptions that are thrown from an action to a result.
15 Params sets the action's request parameters.
16

 

fileUpload

allows for simple file uploading.
17 i18n keeps track of the user's session's chosen locale.

These were some of the default interceptors which are already present in the struts2.

Now let us see an example of interceptors in use.

Example

Let's see how to apply an interceptor that is already in existence to our "Hello World" programme. To determine how long it took to complete an action method, we will employ the timer interceptor. In addition, We will be using a params interceptor, whose goal is to transmit the action's request arguments. Without utilising this interceptor, you can test your example and discover that the name property is not being set because the argument cannot connect to the operation.

Let us consider an already created application named “Helloworldstruts” and see the following code.

 

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name = "struts.devMode" value = "true" />
   
   <package name = "helloworld" extends = "struts-default">
      <action name = "hello" 
         class = "com.codingninjas.struts2.HelloWorldAction"
         method = "execute">
         <interceptor-ref name = "params"/>
         <interceptor-ref name = "timer" />
         <result name = "success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>


The above code, when executed, displays the following output.

Output

When we input any value inside the text bar, it will display the following log, which contains the total time taken to complete the execution. It is being displayed because of the timer interceptor.

INFO: Server startup in 3539 ms
30/08/2022 8:40:53 PM 
com.opensymphony.xwork2.util.logging.commons.CommonsLogger info
INFO: Executed action [//hello!execute] took 109 ms.


Let us now see some advantages of using interceptors in the struts.

Advantages

There is no need to relaunch the application to remove any concerns, such as validation, exception handling, logging, etc. We simply need to remove the entry from the struts.xml file.

So these utilities of the interceptors are the advantages of using them in struts.

With this blog, we come to the end of this blog. Let us answer some of the frequently asked questions related to this blog.

Frequently asked questions

What is Struts Framework? and its Components?

The Online Application Development Framework known as Struts offers a good framework for creating web apps. Servlets, JSPs, custom tags, and message resources are all incorporated within the Struts framework.

Why do we use Struts?

Because Struts is built on the Model, View, Controller (MVC) architecture, which separates business logic, design, and controller, the code is easier to write, maintain, and read.

What are some of the new features of Struts2?

The following are some of Struts2's standout features.

The Action class in Struts 2 is a POJO. We don't have to implement any interfaces or inherit any classes.

JSP, Free Marker, and Valocity are available in Struts2 for the view component.

Front Controller is StrutsPrepareAndExecuteFilter in Struts2.

Struts2 requires that the configuration file be named struts.xml and stored in the classes directory.

While processing the request, Struts2 use the Interceptors concept.

What do you mean by Interceptors?

The object known as an interceptor is used to offer pre-processing logic before action is called or post-processing logic after the action is called. Interceptors can be used for a variety of tasks, including validations, handling exceptions, file uploads, displaying preliminary findings, etc.

What is the function of the Struts.xml File in Struts?

The user can specify every mapping to actions in the struts.xml file so that a certain action is called whenever a specific operation is carried out. It is located in the WEB-INF/classes folder, also known as the configuration file.

Conclusion

In this blog, we have extensively discussed the interceptors in struts. We saw many default interceptors and their implementation along with their outputs. Anything in constant usage will have some advantages and so do the interceptors, so we also discussed the advantages it, and in the end, we discussed some of the frequently asked questions related to this.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol 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.

Thankyou image
Live masterclass