YouTube Icon

Interview Questions.

Top 100+ Apache Struts 2 Interview Questions And Answers - May 26, 2020

fluid

Top 100+ Apache Struts 2 Interview Questions And Answers

Question 1. What Is Struts2?

Answer :

Struts2 is popular and mature net application framework primarily based at the MVC layout sample. Struts2 isn't always just the following model of Struts 1, but it's miles a complete rewrite of the Struts structure.

Question 2. Name Some Of The Features Of Struts2?

Answer :

Here are a number of the awesome capabilities that can force you to recall Struts2 −

POJO forms and POJO movements − Struts2 has finished away with the Action Forms that were an vital a part of the Struts framework. With Struts2, you could use any POJO to get hold of the form enter. Similarly, you may now see any POJO as an Action class.

Tag help − Struts2 has progressed the form tags and the new tags permit the developers to jot down much less code.

AJAX support − Struts2 has regarded the take over by Web2.Zero technology, and has incorporated AJAX help into the product with the aid of growing AJAX tags, that characteristic very much like the usual Struts2 tags.

Easy Integration − Integration with other frameworks like Spring, Tiles and SiteMesh is now simpler with a spread of integration available with Struts2.

Template Support − Support for generating perspectives the use of templates.

Plugin Support − The core Struts2 behaviour may be greater and augmented by means of the usage of plugins. A variety of plugins are to be had for Struts2.

Apache Tapestry Interview Questions
Question three. What Are The Core Components Of A Struct2 Based Application?

Answer :

The Model-View-Controller sample in Struts2 is found out with following 5 middle additives −

Actions
Interceptors
Value Stack / OGNL
Results / Result sorts
View technologies
Question 4. Explain The Life Cycle Of A Request In Struct2 Application?

Answer :

Following is the existence cycle of a request in Struct2 software −

User sends a request to the server for soliciting for for some aid (i.E pages).
The FilterDispatcher seems at the request and then determines the right Action.
Configured interceptors functionalities applies together with validation, report add and so forth.
Selected action is completed to perform the asked operation.
Again, configured interceptors are implemented to do any submit-processing if required.
Finally the result is ready through the view and returns the result to the person.
Apache Tapestry Tutorial
Question 5. What Is The Purpose Of Struts.Xml In Struct2?

Answer :

The struts.Xml file carries the configuration facts that you will be enhancing as actions are developed. This document may be used to override default settings for an utility, as an example struts.DevMode = false and other settings that are defined in belongings record. This document may be created beneath the folder WEB-INF/classes.

Apache Cassandra Interview Questions
Question 6. What Is The Purpose Of Constant Tag In Struts.Xml?

Answer :

The consistent tag together with call and value attributes may be used to override any of the subsequent residences described in default.Residences, like we just set struts.DevMode property. Setting struts.DevMode property allows us to see more debug messages within the log document.

Question 7. What Is The Purpose Of Action Tag In Struts.Xml?

Answer :

We outline motion tags corresponds to every URL we want to get right of entry to and we define a category with execute() approach as a way to be accessed on every occasion we will get entry to corresponding URL.

Results decide what gets lower back to the browser after an movement is done. The string returned from the motion must be the name of a result. Results are configured in keeping with-action as above, or as a "worldwide" result, available to every motion in a package. Results have optionally available call and kind attributes. The default call price is "success".

Apache Cassandra Tutorial Apache Spark Interview Questions
Question 8. What Is The Purpose Of Struct-config.Xml In Struct2?

Answer :

The struts-config.Xml configuration record is a hyperlink between the View and Model components within the Web Client.

Question 9. What Is The Purpose Of Form-beans Tag In Struct-config.Xml?

Answer :

This is where you map your ActionForm subclass to a call. You use this name as an alias to your ActionForm in the course of the rest of the struts-config.Xml document, or even on your JSP pages.

Apache Solr Interview Questions
Question 10. What Is The Purpose Of Global-forwards Tag In Struct-config.Xml?

Answer :

This phase maps a page in your webapp to a call. You can use this call to consult the real page. This avoids hardcoding URLs for your net pages.

Apache Solr Tutorial
Question eleven. What Is The Purpose Of Action-mappings Tag In Struct-config.Xml?

Answer :

This is where you claim shape handlers and they're additionally called motion mappings.

Apache Storm Interview Questions
Question 12. What Is The Purpose Of Plug-in Tag In Struct-config.Xml?

Answer :

This section tells Struts in which to locate your residences files, which comprise activates and errors messages.

Apache Tapestry Interview Questions
Question thirteen. What Is The Purpose Of Struts.Houses In Struct2?

Answer :

This configuration file affords a mechanism to exchange the default behavior of the framework. Actually all the homes contained in the struts.Properties configuration report can also be configured within the internet.Xml using the init-param, as well using the constant tag inside the struts.Xml configuration file. But if you want to maintain the things separate and more struts unique then you may create this report beneath the folder WEB-INF/instructions. The values configured on this record will override the default values configured in default.Houses that is contained within the struts2-center-x.Y.Z.Jar distribution.

Apache Storm Tutorial
Question 14. What Are Interceptors In Struts 2?

Answer :

Interceptors are conceptually the same as servlet filters or the JDKs Proxy magnificence. Interceptors permit for crosscutting functionality to be implemented one after the other from the action in addition to the framework.

You can obtain the subsequent the use of interceptors :

Providing preprocessing logic earlier than the action is referred to as.
Providing postprocessing good judgment after the action is called.
Catching exceptions in order that alternate processing may be performed.
Question 15. How Can You Create Your Custom Interceptor In Struts 2?

Answer :

Creating a custom interceptor is simple; the interface that desires to be extended is the Interceptor interface.

Apache Hive Interview Questions
Question sixteen. How Interceptor Works In Struts 2?

Answer :

Actual action will be executed using the interceptor via invocation.Invoke() call. So you may do a little pre-processing and a few submit-processing primarily based on your requirement.
The framework itself starts offevolved the manner by means of making the first call to the ActionInvocation item's invoke(). Each time invoke() is referred to as, ActionInvocation consults its nation and executes whichever interceptor comes subsequent. When all the configured interceptors were invoked, the invoke() approach will purpose the motion itself to be completed.
Apache Hive Tutorial
Question 17. What Are Result Types In Struts?

Answer :

The Action elegance manages the application's country, and the Result Type manages the view.

Apache Pig Interview Questions
Question 18. What Is Defeult Result Type?

Answer :

Default end result kind is dispatcher, which is used to dispatch to JSP pages.

Apache Cassandra Interview Questions
Question 19. What Is The Purpose Of Dispatcher Result Type?

Answer :

The dispatcher result type is the default kind, and is used if no different result type is unique. It's used to ahead to a servlet, JSP, HTML web page, and so on, on the server. It uses the RequestDispatcher.Forward() approach.

Apache Pig Tutorial
Question 20. What Is The Purpose Of Redirect Result Type?

Answer :

The redirect end result type calls the usual reaction.SendRedirect() method, inflicting the browser to create a new request to the given place. We can provide the region both in the body of the <result...> detail or as a <param name="location"> element.

Apache Flume Interview Questions
Question 21. What Is Value Stack?

Answer :

The value stack is a fixed of several items which maintains the following items within the provided order −

Temporary Objects − There are diverse temporary objects which are created throughout execution of a page. For example the contemporary iteration value for a collection being looped over in a JSP tag.

The Model Object − If you're using version gadgets on your struts application, the current model item is located before the action on the cost stack.

The Action Object − This could be the current action object which is being done.

Named Objects − These gadgets consist of #software, #consultation, #request, #attr and #parameters and discuss with the corresponding servlet scopes.

Question 22. What Is Ognl?

Answer :

The Object-Graph Navigation Language (OGNL) is a effective expression language this is used to reference and control information at the ValueStack. OGNL also allows in records transfer and kind conversion.

Apache Flume Tutorial
Question 23. Which Components Are Available Using Actioncontext Map?

Answer :

The ActionContext map consists of the following −

software − utility scoped variables.

Consultation − consultation scoped variables.

Root / value stack − all your movement variables are saved here.

Request − request scoped variables.

Parameters − request parameters.

Atributes − the attributes saved in page, request, session and application scope.

Apache Kafka Interview Questions
Question 24. Which Interceptor Is Responsible For File Upload Support?

Answer :

File uploading in Struts is feasible through a pre-defined interceptor referred to as FileUpload interceptor which is to be had through the org.Apache.Struts2.Interceptor.FileUploadInterceptor magnificence and protected as part of the defaultStack.

Apache Spark Interview Questions
Question 25. What Are The Struts2 Configuration Properties That Control File Uploading Process?

Answer :

Following are the Struts2 configuration homes that manipulate report importing manner −

struts.Multipart.MaxSize − The maximum size (in bytes) of a file to be widespread as a document upload. Default is 250M.

Struts.Multipart.Parser − The library used to upload the multipart form. By default is jakarta.

Struts.Multipart.SaveDir − The region to shop the temporary document. By default is javax.Servlet.Context.Tempdir.

Apache Kafka Tutorial
Question 26. What Are The Struts2 Error Message Keys That Can Come During File Uploading Process?

Answer :

The fileUplaod interceptor makes use of numerous default mistakes message keys −

struts.Messages.Errors.Importing − A wellknown errors that occurs when the record couldn't be uploaded.

Struts.Messages.Error.Report.Too.Massive − Occurs whilst the uploaded file is simply too large as detailed via maximumSize.

Struts.Messages.Mistakes.Content.Kind.Not.Allowed − Occurs while the uploaded record does no longer fit the expected content material kinds specific.

Apache Ant Interview Questions
Question 27. How To Override The Default Error Message That Can Come During File Uploading Process?

Answer :

You can override the textual content of these messages in WebContent/WEB-INF/classes/messages.Homes resource files.

Apache Solr Interview Questions
Question 28. What Is Structs 2 Validation Framework?

Answer :

At Struts's middle, we've got the validation framework that assists the utility to run the guidelines to perform validation earlier than the action technique is carried out. Action magnificence need to expand the ActionSupport class, on the way to get the validate approach achieved.

Apache Ant Tutorial
Question 29. How Struts 2 Validation Works?

Answer :

When the user presses the submit button, Struts 2 will mechanically execute the validate technique and if any of the if statements indexed in the approach are true, Struts 2 will name its addFieldError method. If any mistakes had been introduced then Struts 2 will not proceed to call the execute approach. Rather the Struts 2 framework will return input as the end result of calling the action.
So whilst validation fails and Struts 2 returns enter, the Struts 2 framework will redisplay the view document. Since we used Struts 2 shape tags, Struts 2 will automatically upload the mistake messages simply above the form filed.
These blunders messages are those we targeted inside the addFieldError approach name. The addFieldError method takes  arguments. The first is the form subject name to which the error applies and the second is the mistake message to display above that shape discipline.
Apache Camel Interview Questions
Question 30. What Is Xml Based Validation In Struts2?

Answer :

The second method of doing validation is with the aid of setting an xml document next to the action class. Struts2 XML based totally validation gives more options of validation like e mail validation, integer variety validation, form validation subject, expression validation, regex validation, required validation, requiredstring validation, stringlength validation and and so forth.

Question 31. What Should Be The Name Of Xml File Used For Validation In Struts?

Answer :

The xml report wishes to be named '[action-class]'-validation.Xml.

Apache Tajo Tutorial
Question 32. What Types Of Validations Are Available In Xml Based Validation In Struts2?

Answer :

Following is the listing of numerous kinds of field level and non-field level validation to be had in Struts2 −

date validator
double validator
email validator
expression validator
int validator
regex validator
required validator
requiredstring validator
stringlength validator
url validator
Apache Tajo Interview Questions
Question 33. What Is Internationalization?

Answer :

Internationalization (i18n) is the method of planning and imposing services and products with the intention to without problems be tailored to unique neighborhood languages and cultures, a procedure known as localization. The internationalization process is occasionally called translation or localization enablement.

Apache Storm Interview Questions
Question 34. How Struts2 Supports Internationalization?

Answer :

Struts2 offers localization ie. Internationalization (i18n) assist through resource bundles, interceptors and tag libraries within the following places −

The UI Tags.
Messages and Errors.
Within action instructions.
Question 35. What Is The Naming Convention For A Resource Bundle File In Struts2?

Answer :

The most effective naming layout for a aid document is −

bundlename_language_country.Homes

Here bundlename might be ActionClass, Interface, SuperClass, Model, Package, Global aid residences. Next element language_country represents the us of a locale as an instance Spanish (Spain) locale is represented with the aid of es_ES and English (United States) locale is represented by means of en_US and so forth. Here you may bypass u . S . Component that is non-obligatory.

Question 36. In Which Order Struts Framework Searches For A Message Bundle?

Answer :

When you reference a message element by means of its key, Struts framework searches for a corresponding message package within the following order −

ActionClass.Properties
Interface.Properties
SuperClass.Residences
model.Properties
bundle.Homes
struts.Homes
worldwide.Residences
Apache Hive Interview Questions
Question 37. Which Class Of Struts Is Responsible To Converts Data Types From String And Vice Versa?

Answer :

StrutsTypeConverter elegance tells Struts a way to convert Environment to a String and vice versa through overriding two strategies convertFromString() and convertToString().

Question 38. What Inbuilt Themes Are Provided By Struts2?

Answer :

Struts 2 comes with three built-in themes −

simple subject matter − A minimum theme with out a "bells and whistles". For instance, the textfield tag renders the HTML <input/> tag without a label, validation, error reporting, or every other formatting or capability.

Xhtml subject matter − This is the default topic utilized by Struts 2 and offers all the fundamentals that the simple theme provides and adds several capabilities like widespread two-column desk layout for the HTML, Labels for each of the HTML, Validation and mistakes reporting and so forth.

Css_xhtml topic − This subject provides all the basics that the easy topic provides and provides several capabilities like wellknown -column CSS-based format, using <div> for the HTML Struts Tags, Labels for every of the HTML Struts Tags, located in line with the CSS stylesheet.

Question 39. How To Handle Exceptions In Structs?

Answer :

Struts makes the exception dealing with easy by using the use of the "exception" interceptor. The "exception" interceptor is covered as a part of the default stack, so that you do not ought to do something greater to configure it. It is available out-of-the-box geared up with the intention to use.

Question forty. What Is The Purpose Of @effects Annotation?

Answer :

A @Results annotation is a group of effects. Under the @Results annotation, we will have a couple of @Result annotations.

@Results(

   @Result(name="fulfillment", cost="/achievement.Jsp"),

   @Result(name="blunders", cost="/mistakes.Jsp")

)

public magnificence Employee extends ActionSupport

 ...

Apache Pig Interview Questions
Question forty one. What Is The Purpose Of @end result Annotation?

Answer :

The @result annotations have the call that correspond to the outcome of the execute method. They additionally include a area as to which view have to be served similar to return cost from execute().

@Result(name="fulfillment", value="/success.Jsp")

public elegance Employee extends ActionSupport

 ...

Question forty two. What Is The Purpose Of @motion Annotation?

Answer :

This is used to decorate the execute() technique. The Action approach additionally takes in a cost that is the URL on which the action is invoked.

Public class Employee extends ActionSupport

   personal String call;

   private int age;

   @Action(fee="/empinfo")

   public String execute() 

   

       return SUCCESS;

   

Apache Flume Interview Questions
Question 43. What Is The Purpose Of @after Annotation?

Answer :

The @After annotation marks a action method that needs to be referred to as after the principle action approach and the result become completed. Return fee is left out.

Public magnificence Employee extends ActionSupport

   @After

   public void isValid() throws ValidationException 

      // validate model item, throw exception if failed

   

   public String execute() 

      // perform secure motion

      return SUCCESS;

   

Question 44. What Is The Purpose Of @before Annotation?

Answer :

The @Before annotation marks a movement method that wishes to be known as earlier than the main action approach and the result changed into accomplished. Return fee is disregarded.

Public magnificence Employee extends ActionSupport

   @Before

   public void isAuthorized() throws AuthenticationException 

      // authorize request, throw exception if failed

   

   public String execute() 

      // perform comfy motion

      go back SUCCESS;

   

Question forty five. What Is The Purpose Of @beforeresult Annotation?

Answer :

The @BeforeResult annotation marks a movement approach that needs to be completed earlier than the end result. Return price is overlooked.

Public class Employee extends ActionSupport

   @BeforeResult

   public void isValid() throws ValidationException 

    // validate model object, throw exception if failed

   

   public String execute() 

      // carry out movement

      go back SUCCESS;

   

Question 46. What Is The Purpose Of @conversionerrorfieldvalidator Annotation?

Answer :

This validation annotation assessments if there are any conversion mistakes for a field and applies them if they exist.

Public class Employee extends ActionSupport

   @ConversionErrorFieldValidator(message = "Default message", 

                        key = "i18n.Key", shortCircuit = genuine)

   public String getName() 

       go back call;

   

Question 47. What Is The Purpose Of @doublerangefieldvalidator Annotation?

Answer :

his validation annotation tests that a double discipline has a fee inside a specific variety. If neither min nor max is about, nothing might be finished.

Public elegance Employee extends ActionSupport

   @DoubleRangeFieldValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = true, 

   minInclusive = "zero.123", maxInclusive = "ninety nine.987")

   public String getIncome() 

       return profits;

   

Question 48. What Is The Purpose Of @emailvalidator Annotation?

Answer :

This validation annotation exams that a area is a legitimate e mail address if it incorporates a non-empty String.

Public elegance Employee extends ActionSupport

   @EmailValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = genuine)

   public String getEmail() 

       go back e mail;

   

Question 49. What Is The Purpose Of @expressionvalidator Annotation?

Answer :

This non-discipline stage validator validates a furnished normal expression.

@ExpressionValidator(message = "Default message", key = "i18n.Key", shortCircuit = authentic, expression = "an OGNL expression" )

Question 50. What Is The Purpose Of @intrangefieldvalidator Annotation?

Answer :

This validation annotation assessments that a numeric subject has a value inside a detailed range. If neither min nor max is set, nothing could be performed.

Public elegance Employee extends ActionSupport

   @IntRangeFieldValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = true, 

   min = "zero", max = "42")

   public String getAge() 

       go back age;

   

Question fifty one. What Is The Purpose Of @requiredstringvalidator Annotation?

Answer :

This validation annotation tests that a String area is not empty (i.E. Non-null with a length > zero).

Public magnificence Employee extends ActionSupport

   @RequiredStringValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = true, trim = authentic)

   public String getName() 

       return call;

   

Question 52. What Is The Purpose Of @stringlengthfieldvalidator Annotation?

Answer :

This validator tests that a String area is of the right length. It assumes that the field is a String. If neither minLength nor maxLength is about, not anything could be carried out.

Public magnificence Employee extends ActionSupport

   @StringLengthFieldValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = actual, 

   trim = true, minLength = "5",  maxLength = "12")

   public String getName() 

       return name;

   

Question 53. What Is The Purpose Of @urlvalidator Annotation?

Answer :

This validator tests that a subject is a legitimate URL.

Public magnificence Employee extends ActionSupport

   @UrlValidator(message = "Default message", 

   key = "i18n.Key", shortCircuit = true)

   public String getURL() 

       return url;

   

Question 54. What Is The Purpose Of @validations Annotation?

Answer :

If you need to use several annotations of the same kind, these annotation must be nested within the @Validations() annotation.

Public class Employee extends ActionSupport

  @Validations(

   requiredFields =

      @RequiredFieldValidator(type = ValidatorType.SIMPLE, 

      fieldName = "customfield", 

      message = "You have to enter a cost for discipline."),

   requiredStrings =

      @RequiredStringValidator(kind = ValidatorType.SIMPLE, 

      fieldName = "stringisrequired", 

      message = "You need to enter a fee for string.")

   )

   public String getName() 

       go back call;

   

Question 55. What Is The Purpose Of @customvalidator Annotation?

Answer :

This annotation can be used for custom validators. Use the ValidationParameter annotation to deliver extra params.

@CustomValidator(type ="customValidatorName", fieldName = "myField")

Question 56. What Is The Purpose Of @conversion Annotation Annotation?

Answer :

This is a marker annotation for type conversions at Type level. The Conversion annotation have to be carried out at Type level.

@Conversion()

   public magnificence ConversionAction implements Action 

Question 57. What Is The Purpose Of @createifnull Annotation Annotation?

Answer :

This annotation sets the CreateIfNull for type conversion. The CreateIfNull annotation ought to be implemented at area or method degree.

@CreateIfNull( fee = true )

private List<User> customers;

Question fifty eight. What Is The Purpose Of @detail Annotation Annotation?

Answer :

This annotation sets the Element for type conversion. The Element annotation should be implemented at discipline or technique degree.

@Element( fee = com.Acme.User )

private List<User> userList;

Question 59. What Is The Purpose Of @key Annotation Annotation?

Answer :

This annotation units the Key for kind conversion. The Key annotation have to be applied at subject or approach level.

@Key( value = java.Lang.Long.Class )

private Map<Long, User> userMap;

Question 60. What Is The Purpose Of @keyproperty Annotation Annotation?

Answer :

This annotation sets the KeyProperty for kind conversion. The KeyProperty annotation should be carried out at area or technique degree.

@KeyProperty( cost = "userName" )

included List<User> customers = null;

Question sixty one. What Is The Purpose Of @typeconversion Annotation Annotation?

Answer :

This annotation annotation is used for sophistication and application huge conversion policies. The TypeConversion annotation may be carried out at property and technique level.

@TypeConversion(rule = ConversionRule.COLLECTION, 

converter = "java.Util.String")

public void setUsers( List users ) 

   this.Customers = customers;

Question sixty two. What Are Struts2 Core Components?

Answer :

Struts2 center components are: A.Action Classes B.Interceptors C.Result Pages, JSP of FreeMarker templates D.ValueStack, OGNL and Tag Libraries .

Question sixty three. Which Interceptor Is Responsible For I18n Support?

Answer :

com.Opensymphony.Xwork2.Interceptor.I18nInterceptor interceptor is chargeable for i18n aid in Struts2 packages. This interceptor is configured in struts-default package with name “i18n” and it’s a part of i18nStack and defaultStack.

Question 64. What Is The Difference In Using Action Interface And Actionsupport Class For Our Action Classes, Which One You Would Prefer?

Answer :

We can put into effect Action interface to create our action training. This interface has a unmarried approach execute() that we want to enforce. The only gain of using this interface is that it contains some constants that we can use for end result pages, these constants are SUCCESS, ERROR, NONE, INPUT and LOGIN. 

ActionSupport elegance is the default implementation of Action interface and it additionally implements interfaces related to Validation and i18n help. ActionSupport magnificence implements Action, Validateable, ValidationAware, TextProvider and LocaleProvider interfaces. We can override validate() approach of ActionSupport elegance to include subject degree validation login in our motion training. 

Depending on the requirements, we are able to use any of the procedures to create struts 2 movement instructions, my favorite is ActionSupport magnificence because it facilitates in writing validation and i18n good judgment without problems in movement training.

Question 65. How Can We Get Servlet Api Request, Response, Httpsession Etc Objects In Action Classes?

Answer :

Struts2 motion instructions doesn’t provide direct get entry to to Servlet API additives along with Request, Response and Session. However every so often we need those get right of entry to in action lessons along with checking HTTP approach or putting cookies in response. 

That's why Struts2 API affords a group of *Aware interfaces that we will enforce to access those objects. Struts2 API uses dependency injection to inject Servlet API components in motion training. Some of the vital Aware interfaces are SessionAware, ApplicationAware, ServletRequestAware and ServletResponseAware.

Question 66. What Are Different Ways To Create Action Classes In Struts2?

Answer :

Struts2 offer one of a kind methods to create motion classes. 

By implementing Action interface
Using Struts2 @Action annotation
By extending ActionSupport elegance
Any everyday java magnificence with execute() method returning String can be configured as Action magnificence.
Question sixty seven. What Is The Use Of Execandwait Interceptor?

Answer :

Struts2 presents execAndWait interceptor for long strolling movement training. We can use this interceptor to return an intermediate response web page to the customer and once the processing is finished, very last response is again to the customer. This interceptor is defined inside the struts-default bundle and implementation is found in ExecuteAndWaitInterceptor elegance.

Question sixty eight. Does Struts2 Action And Interceptors Are Thread Safe?

Answer :

Struts2 Action training are thread secure because an item is instantiated for each request to handle it. 
Struts2 interceptors are singleton classes and a brand new thread is created to address the request, so it’s not thread secure and we want to enforce them carefully to avoid any troubles with shared facts.
Question sixty nine. What Is The Use Of Token Interceptor In Struts2?

Answer :

One of the essential issues with internet programs is the double shape submission. If now not taken care, double shape submission could result in charging double amount to customer or updating database values two times. We can use token interceptor to solve the double shape submission problem. This interceptor is defined in struts-default bundle however it’s now not a part of any interceptor stack, so we need to consist of it manually in our movement instructions.

Question 70. How Can We Integrate Log4j In Struts2 Application?

Answer :

Struts2 provides clean integration of log4j API for logging motive, all we want to have is log4j configuration document within the WEB-INF/training listing.

Question seventy one. Which Class Is The Front Controller In Struts2?

Answer :

org.Apache.Struts2.Dispatcher.Ng.Filter.StrutsPrepareAndExecuteFilter is the Front Controller elegance in Struts2 and each request processing starts offevolved from this magnificence. Earlier versions of Struts2 makes use of org.Apache.Struts2.Dispatcher.FilterDispatcher as Front Controller magnificence

Question seventy two. What Are Different Struts2 Tags? How Can We Use Them?

Answer :

Struts2 presents a variety of custom tags that we will use in result pages to create views for client request. These tags are widely divided into 3 categories- Data tags, Control tags and UI tags. 

We can use these tags by means of adding these in JSP pages the use of taglib directive.

< %@ taglib uri="/struts-tags" prefix="s" % >>

Question 73. What Is Custom Type Converter In Struts2?

Answer :

Struts2 guide OGNL expression language and it performs two essential tasks in Struts 2 – information transfer and sort conversion. 

OGNL is flexible and we can easily make bigger it to create our own custom converter elegance. Creating and configuring custom type converter class may be very smooth, first step is to repair the enter layout for the custom magnificence. Second step is to implement the converter magnificence. Type converter instructions ought to enforce com.Opensymphony.Xwork2.Conversion.TypeConverter interface. Since in web application, we continually get the request in form of String and send reaction in the shape of String, Struts 2 API gives a default implementation of TypeConverter interface, StrutsTypeConverter. StrutsTypeConverter includes two summary methods – convertFromString to transform String to Object and convertToString to transform Object to String.

Question 74. What Are The Benefits Of Interceptors In Struts2?

Answer :

Some of the blessings of interceptors are: 

Interceptor performs a crucial position in achieving excessive level of separation of concerns.
Struts2 interceptors are configurable, we are able to configure it for any movement we need.
We can create our own custom interceptors to carry out a few commonplace duties which include request params logging, authentication and so forth. This facilitates us in taking care of commonplace obligations at a single area, attaining low upkeep value.
We can create interceptors stack to apply with special moves.
Question 75. What Is Valuestack And Ognl?

Answer :

ValueStack is the storage region in which the application data is saved via Struts2 for processing the customer requests. The statistics is stored in ActionContext items that use ThreadLocal to have values specific to the unique request thread. 

Object-Graph Navigation Language (OGNL) is a effective Expression Language this is used to govern statistics saved on the ValueStack. As you can see in architecture diagram, each interceptors and result pages can get right of entry to statistics stored on ValueStack using OGNL.

Question seventy six. What Is Life Cycle Of An Interceptor?

Answer :

Interceptor interface defines 3 techniques – init(), ruin() and intercept(). Init and wreck are the existence cycle methods of an interceptor. Interceptors are Singleton training and Struts2 initialize a brand new thread to deal with every request. Init() approach is referred to as whilst interceptor instance is created and we can initialize any assets in this approach. Wreck() technique is called while application is shutting down and we are able to launch any sources in this technique. 

Question seventy seven. What Is Struts-default Package And What Are It’s Benefits?

Answer :

struts-default is an summary package that defines all of the Struts2 interceptors and commonly used interceptor stack. It is really useful to extend this bundle whilst configuring our utility package to keep away from configuring interceptors once more. This is furnished to help developers by disposing of the trivial undertaking of configuring interceptor and end result pages in our application.

Question seventy eight. Name Some Useful Annotations Introduced In Struts2?

Answer :

Some of the important annotations brought in Struts2 are: 

@Action to create movement elegance
@Actions to configure single elegance for multiple actions
@Namespace and @Namespaces for growing special modules
@Result for result pages
@ResultPath for configuring result pages area
Question 79. What Is An Interceptor Stack?

Answer :

An interceptor stack allows us to organization collectively multiple interceptors in a bundle for in addition use. Struts-default package creates some of the frequently used interceptor stack – basicStack and defaultStack. We can create our personal interceptor stack at the start of the bundle after which configure our action classes to use it.

Question eighty. What Is The Default Suffix For Struts2 Action Uri And How Can We Change It?

Answer :

The default URI suffix for Struts2 action is .Motion, in Struts1 default suffix changed into .Do. We can exchange this suffix by using defining struts.Movement.Extension constant price in our Struts2 configuration record as:

< constant name="struts.Action.Extension" value="action,do" > < /constant >

Question eighty one. Provide Some Important Struts2 Constants That You Have Used?

Answer :

Some of the Struts2 constants that I have used are: 

struts.DevMode to run our software in improvement mode. This mode does reload houses documents and gives greater logging and debugging feature. It’s very beneficial at the same time as growing our software however we should flip it off whilst moving our code to production. 
Struts.Conference.End result.Direction to configure the location of result pages. By default Struts2 look for end result pages at WEBAPP-ROOT/Namespace/ and we are able to alternate the vicinity with this steady. 
Struts.Custom.I18n.Sources to define international aid bundle for i18n assist. 
Struts.Action.Extension to configure the URL suffix to for Struts2 software. Default suffix is .Movement however every now and then we would want to trade it to . Do or something else. 
We can configure above constants in struts.Xml document like underneath. 

< constant name="struts.DevMode" value="true" > < /constant >

< constant name="struts.Action.Extension" value="action,do" > < /constant >

< constant name="struts.Custom.I18n.Resources" value="global" > < /constant >

< constant name="struts.Convention.Result.Path" value="/" > < /constant >

Question 82. How Can We Upload Files In Struts2 Application?

Answer :

File Upload is one of the common challenge in an internet utility. Thats why Struts2 offers constructed in guide for record add through FileUploadInterceptor. This interceptor is configured in struts-default bundle and offer alternatives to set the most size of a file and record types that can be uploaded to the server.

Question 83. What Is The Use Of Namespace In Action Mapping In Struts2?

Answer :

Struts2 namespace configuration allows us to create modules easily. We can use namespace to split our movement lessons based on their capability, as an instance admin, consumer, patron and many others.

Question 84. Which Interceptor Is Responsible For Mapping Request Parameters To Action Class Java Bean Properties?

Answer :

com.Opensymphony.Xwork2.Interceptor.ParametersInterceptor interceptor is chargeable for mapping request parameters to the Action magnificence java bean homes. This interceptor is configured in struts-default package deal with call “params”. This interceptor is part of basicStack and defaultStack interceptors stack.

Question 85. What Are Best Practices To Follow While Developing Struts2 Application?

Answer :

Some of the first-rate practices even as growing Struts2 application are: 

Always try to enlarge struts-default package deal while growing your bundle to keep away from code redundancy in configuring interceptors. 
For common duties across the software, which includes logging request params, attempt to use interceptors. 
Always keep action classes java bean residences in a separate bean for code reuse and implement ModelDriven interface. 
If you have custom interceptor that you may use in a couple of moves, create interceptor stack for that and then use it. 
Try to divide your software in specific modules with namespace configuration based on useful regions. 
Try to apply Struts2 tags in end result pages for code clarify, if wanted create your own kind converters. 
Use improvement mode for quicker improvement, however make sure manufacturing code doesn’t run in dev mode. 
Use Struts2 i18n help for aid bundles and to assist localization. 
Struts2 provides a variety of places in which you may have resource bundles but try and hold one worldwide useful resource package deal and one for action class to avoid confusion. 
Struts-default package deal configures all of the interceptors and creates distinct interceptor stacks. Try to apply most effective what is wanted, for instance in case you don’t have localization requirement, you may keep away from i18n interceptor.
Question 86. What Is The Default Location Of Result Pages And How Can We Change It?

Answer :

By default Struts2 appears for end result pages in WEBAPP-ROOT/Namespace/ directory but occasionally we want to maintain end result pages in another area, we are able to provide struts.Conference.Result.Direction consistent fee in Struts2 configuration document to trade the end result pages vicinity. 

Another way is to use @ResultPath annotation in motion instructions to offer the result pages area.




CFG