Top 50 Apache Struts 2 Interview Questions
Q1. What Is The Purpose Of
This annotation may be used for custom validators. Use the ValidationParameter annotation to deliver extra params.
@CustomValidator(type ="customValidatorName", fieldName = "myField")
Q2. How Struts 2 Validation Works?
When the user presses the submit button, Struts 2 will routinely execute the validate technique and if any of the if statements indexed in the approach are actual, Struts 2 will name its addFieldError method. If any mistakes were delivered then Struts 2 will now not proceed to call the execute method. Rather the Struts 2 framework will return enter because the end result of calling the action.
So whilst validation fails and Struts 2 returns enter, the Struts 2 framework will redisplay the view record. Since we used Struts 2 form tags, Struts 2 will routinely upload the mistake messages just above the form filed.
These blunders messages are those we specific within the addFieldError method call. The addFieldError method takes arguments. The first is the form area name to which the error applies and the second is the mistake message to display above that shape area.
Q3. What Is The Purpose Of
This annotation sets the KeyProperty for type conversion. The KeyProperty annotation have to be applied at subject or technique level.
@KeyProperty( price = "userName" )
blanketed List<User> users = null;
Q4. In Which Order Struts Framework Searches For A Message Bundle?
When you reference a message detail via its key, Struts framework searches for a corresponding message package inside the following order −
ActionClass.Houses
Interface.Residences
SuperClass.Houses
model.Homes
package.Houses
struts.Properties
international.Residences
Q5. What Is The Purpose Of
This annotation units the Key for kind conversion. The Key annotation need to be implemented at subject or approach stage.
@Key( fee = java.Lang.Long.Class )
private Map<Long, User> userMap;
Q6. Which Class Of Struts Is Responsible To Converts Data Types From String And Vice Versa?
StrutsTypeConverter magnificence tells Struts how to convert Environment to a String and vice versa via overriding two strategies convertFromString() and convertToString().
Q7. Explain The Life Cycle Of A Request In Struct2 Application?
Following is the lifestyles cycle of a request in Struct2 utility −
User sends a request to the server for inquiring for for some useful resource (i.E pages).
The FilterDispatcher seems at the request after which determines the precise Action.
Configured interceptors functionalities applies together with validation, document upload and so forth.
Selected action is done to perform the requested operation.
Again, configured interceptors are implemented to do any submit-processing if required.
Finally the result is prepared by the view and returns the end result to the person.
Q8. What Is The Purpose Of Form-be Tag In Struct-config.Xml?
This is where you map your ActionForm subclass to a call. You use this call as an alias to your ActionForm in the course of the rest of the struts-config.Xml file, and even for your JSP pages.
Q9. What Is Structs 2 Validation Framework?
At Struts's middle, we've the validation framework that assists the utility to run the policies to carry out validation earlier than the action technique is accomplished. Action class should extend the ActionSupport magnificence, as a way to get the validate technique completed.
Q10. What Is The Purpose Of Dispatcher Result Type?
The dispatcher result type is the default type, and is used if no different end result kind is certain. It's used to ahead to a servlet, JSP, HTML page, and so forth, at the server. It makes use of the RequestDispatcher.Forward() approach.
Q11. What Are Different Struts2 Tags? How Can We Use Them?
Struts2 presents quite a few custom tags that we are able to use in result pages to create views for consumer request. These tags are broadly divided into three categories- Data tags, Control tags and UI tags.
We can use those tags by way of including these in JSP pages using taglib directive.
< %@ taglib uri="/struts-tags" prefix="s" % >>
Q12. What Is The Purpose Of
This validation annotation checks that a String field isn't empty (i.E. Non-null with a duration > 0).
Public class Employee extends ActionSupport
@RequiredStringValidator(message = "Default message",
key = "i18n.Key", shortCircuit = proper, trim = true)
public String getName()
go back name;
Q13. How Can We Get Servlet Api Request, Response, Httpsession Etc Objects In Action Classes?
Struts2 movement instructions doesn’t provide direct get right of entry to to Servlet API additives including Request, Response and Session. However sometimes we want these access in action classes along with checking HTTP method or placing cookies in reaction.
That's why Struts2 API gives a gaggle of *Aware interfaces that we are able to put into effect to get admission to these gadgets. Struts2 API uses dependency injection to inject Servlet API additives in motion training. Some of the crucial Aware interfaces are SessionAware, ApplicationAware, ServletRequestAware and ServletResponseAware.
Q14. What Is The Purpose Of
A @Results annotation is a group of results. Under the @Results annotation, we are able to have multiple @Result annotations.
@Results(
@Result(call="fulfillment", price="/fulfillment.Jsp"),
@Result(name="errors", value="/errors.Jsp")
)
public magnificence Employee extends ActionSupport
...
Q15. What Are The Struts2 Error Message Keys That Can Come During File Uploading Process?
The fileUplaod interceptor makes use of numerous default blunders message keys −
struts.Messages.Blunders.Uploading − A trendy blunders that happens whilst the document could not be uploaded.
Struts.Messages.Blunders.File.Too.Large − Occurs when the uploaded document is simply too huge as distinctive by using maximumSize.
Struts.Messages.Errors.Content material.Type.Not.Allowed − Occurs whilst the uploaded report does now not fit the predicted content material kinds particular.
Q16. What Is The Purpose Of
The @end result annotations have the name that correspond to the final results of the execute method. They also incorporate a place as to which view should be served similar to go back price from execute().
@Result(call="fulfillment", price="/achievement.Jsp")
public magnificence Employee extends ActionSupport
...
Q17. What Is Defeult Result Type?
Default result kind is dispatcher, which is used to dispatch to JSP pages.
Q18. What Is The Purpose Of
his validation annotation checks that a double subject has a price inside a distinctive variety. If neither min nor max is ready, nothing will be performed.
Public elegance Employee extends ActionSupport
@DoubleRangeFieldValidator(message = "Default message",
key = "i18n.Key", shortCircuit = genuine,
minInclusive = "zero.123", maxInclusive = "ninety nine.987")
public String getIncome()
go back income;
Q19. What Are Best Practices To Follow While Developing Struts2 Application?
Some of the quality practices whilst developing Struts2 utility are:
Always try to increase struts-default package deal even as growing your package deal to keep away from code redundancy in configuring interceptors.
For common tasks throughout the software, including logging request params, try to use interceptors.
Always preserve action instructions java bean residences in a separate bean for code reuse and put into effect ModelDriven interface.
If you have custom interceptor that you will use in multiple actions, create interceptor stack for that after which use it.
Try to divide your software in specific modules with namespace configuration primarily based on practical regions.
Try to use Struts2 tags in end result pages for code make clear, if wanted create your personal kind converters.
Use development mode for faster development, however make certain production code doesn’t run in dev mode.
Use Struts2 i18n assist for resource bundles and to guide localization.
Struts2 offers a number of locations wherein you could have resource bundles but try and preserve one worldwide aid bundle and one for motion elegance to avoid confusion.
Struts-default bundle configures all of the interceptors and creates one of a kind interceptor stacks. Try to use handiest what is needed, as an example if you don’t have localization requirement, you could avoid i18n interceptor.
Q20. What Inbuilt Themes Are Provided By Struts2?
Struts 2 comes with three integrated topics −
easy subject matter − A minimum topic with no "bells and whistles". For example, the textfield tag renders the HTML <input/> tag with out a label, validation, error reporting, or any other formatting or functionality.
Xhtml subject matter − This is the default subject matter used by Struts 2 and presents all of the fundamentals that the simple subject matter provides and adds numerous functions like popular -column table format for the HTML, Labels for every of the HTML, Validation and blunders reporting etc.
Css_xhtml subject matter − This theme provides all of the fundamentals that the simple theme presents and provides several features like trendy -column CSS-based totally layout, using <div> for the HTML Struts Tags, Labels for each of the HTML Struts Tags, positioned consistent with the CSS stylesheet.
Q21. How Interceptor Works In Struts 2?
Actual movement can be completed the use of the interceptor with the aid of invocation.Invoke() call. So you could do some pre-processing and a few submit-processing based in your requirement.
The framework itself starts the technique through making the primary call to the ActionInvocation item's invoke(). Each time invoke() is referred to as, ActionInvocation consults its nation and executes whichever interceptor comes next. When all of the configured interceptors were invoked, the invoke() approach will cause the movement itself to be achieved.
Q22. What Is Struts2?
Struts2 is popular and mature internet utility framework based on the MVC layout sample. Struts2 isn't simply the next model of Struts 1, however it's miles a whole rewrite of the Struts structure.
Q23. Which Interceptor Is Responsible For I18n Support?
Com.Opensymphony.Xwork2.Interceptor.I18nInterceptor interceptor is answerable for i18n assist in Struts2 packages. This interceptor is configured in struts-default package with call “i18n” and it’s a part of i18nStack and defaultStack.
Q24. What Is The Difference In Using Action Interface And Actionsupport Class For Our Action Classes, Which One You Would Prefer?
We can put into effect Action interface to create our movement classes. This interface has a unmarried approach execute() that we need to implement. The only benefit of using this interface is that it incorporates a few constants that we are able to use for 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 associated with Validation and i18n assist. ActionSupport magnificence implements Action, Validateable, ValidationAware, TextProvider and LocaleProvider interfaces. We can override validate() method of ActionSupport elegance to encompass area stage validation login in our motion classes.
Depending on the necessities, we are able to use any of the tactics to create struts 2 motion lessons, my favored is ActionSupport class as it helps in writing validation and i18n logic without difficulty in motion training.
Q25. What Is The Purpose Of
The @Before annotation marks a movement technique that desires to be known as earlier than the main motion method and the result changed into achieved. Return price is neglected.
Public class Employee extends ActionSupport
@Before
public void isAuthorized() throws AuthenticationException
// authorize request, throw exception if failed
public String execute()
// carry out comfy motion
go back SUCCESS;
Q26. What Is Value Stack?
The price stack is a fixed of numerous objects which continues the following gadgets within the provided order −
Temporary Objects − There are diverse transient items which might be created at some point of execution of a web page. For example the current iteration cost for a group being looped over in a JSP tag.
The Model Object − If you're the use of version gadgets to your struts utility, the present day model item is positioned earlier than the movement on the cost stack.
The Action Object − This could be the modern action object that is being accomplished.
Named Objects − These objects consist of #utility, #session, #request, #attr and #parameters and seek advice from the corresponding servlet scopes.
Q27. What Is The Purpose Of Action Tag In Struts.Xml?
We define motion tags corresponds to every URL we need to get right of entry to and we define a category with execute() technique so one can be accessed every time we will get admission to corresponding URL.
Results determine what gets lower back to the browser after an motion is completed. The string returned from the movement ought to be the name of a end result. Results are configured in keeping with-action as above, or as a "worldwide" end result, available to every action in a package deal. Results have optional call and type attributes. The default call cost is "success".
Q28. What Is The Purpose Of Struts.Homes In Struct2?
This configuration record offers a mechanism to change the default behavior of the framework. Actually all of the properties contained inside the struts.Properties configuration document can also be configured inside the net.Xml the use of the init-param, as properly the usage of the consistent tag within the struts.Xml configuration file. But if you like to maintain the things separate and greater struts unique then you may create this document under the folder WEB-INF/training. The values configured in this report will override the default values configured in default.Houses that's contained in the struts2-center-x.Y.Z.Jar distribution.
Q29. What Is The Default Suffix For Struts2 Action Uri And How Can We Change It?
The default URI suffix for Struts2 action is .Motion, in Struts1 default suffix was .Do. We can alternate this suffix by using defining struts.Action.Extension constant cost in our Struts2 configuration record as:
< constant name="struts.Action.Extension" value="action,do" > < /constant >
Q30. What Is The Purpose Of
The @BeforeResult annotation marks a movement method that needs to be accomplished earlier than the end result. Return price is disregarded.
Public class Employee extends ActionSupport
@BeforeResult
public void isValid() throws ValidationException
// validate version item, throw exception if failed
public String execute()
// perform motion
go back SUCCESS;
Q31. What Is Life Cycle Of An Interceptor?
Interceptor interface defines three strategies – init(), break() and intercept(). Init and destroy are the life cycle strategies of an interceptor. Interceptors are Singleton training and Struts2 initialize a new thread to handle each request. Init() approach is referred to as when interceptor instance is created and we can initialize any assets in this method. Destroy() technique is referred to as whilst application is shutting down and we will launch any sources on this method.
Q32. What Is An Interceptor Stack?
An interceptor stack facilitates us to group together more than one interceptors in a package for in addition use. Struts-default package creates a number of the in most cases used interceptor stack – basicStack and defaultStack. We can create our personal interceptor stack at the begin of the bundle and then configure our movement classes to use it.
Q33. How Struts2 Supports Internationalization?
Struts2 presents localization ie. Internationalization (i18n) aid via aid bundles, interceptors and tag libraries in the following places −
The UI Tags.
Messages and Errors.
Within action classes.
Q34. What Is The Purpose Of Struts.Xml In Struct2?
The struts.Xml document incorporates the configuration facts that you may be enhancing as actions are developed. This file can be used to override default settings for an utility, for instance struts.DevMode = false and different settings that are described in belongings document. This document may be created underneath the folder WEB-INF/training.
Q35. What Is Custom Type Converter In Struts2?
Struts2 support OGNL expression language and it performs two critical tasks in Struts 2 – data trfer and kind conversion.
OGNL is flexible and we can effortlessly amplify it to create our own custom converter magnificence. Creating and configuring custom kind converter elegance is very easy, first step is to repair the input layout for the custom magnificence. Second step is to put in force the converter magnificence. Type converter classes need to implement com.Opensymphony.Xwork2.Conversion.TypeConverter interface. Since in web software, we usually get the request in form of String and ship reaction in the form of String, Struts 2 API provides a default implementation of TypeConverter interface, StrutsTypeConverter. StrutsTypeConverter includes abstract strategies – convertFromString to transform String to Object and convertToString to transform Object to String.
Q36. What Is The Purpose Of
This annotation sets the Element for type conversion. The Element annotation should be carried out at field or method level.
@Element( price = com.Acme.User )
private List<User> userList;
Q37. Name Some Of The Features Of Struts2?
Here are a number of the outstanding capabilities which could force you to don't forget Struts2 −
POJO forms and POJO movements − Struts2 has carried out away with the Action Forms that have been an imperative a part of the Struts framework. With Struts2, you may use any POJO to receive the form enter. Similarly, you may now see any POJO as an Action magnificence.
Tag aid − Struts2 has stepped forward the shape tags and the brand new tags allow the builders to put in writing less code.
AJAX support − Struts2 has regarded the take over with the aid of Web2.0 technologies, and has included AJAX support into the product via developing AJAX tags, that function very just like the standard Struts2 tags.
Easy Integration − Integration with different frameworks like Spring, Tiles and SiteMesh is now less difficult with a ramification of integration to be had with Struts2.
Template Support − Support for producing views the usage of templates.
Plugin Support − The center Struts2 behaviour may be more desirable and augmented by using the usage of plugins. A variety of plugins are to be had for Struts2.
Q38. What Is The Purpose Of
The @After annotation marks a movement approach that desires to be known as after the principle motion method and the end result become performed. Return price is left out.
Public class Employee extends ActionSupport
@After
public void isValid() throws ValidationException
// validate model object, throw exception if failed
public String execute()
// carry out at ease movement
return SUCCESS;
Q39. What Are Result Types In Struts?
The Action class manages the utility's state, and the Result Type manages the view.
Q40. How To Override The Default Error Message That Can Come During File Uploading Process?
You can override the text of these messages in WebContent/WEB-INF/training/messages.Homes useful resource files.
Q41. What Is The Purpose Of Constant Tag In Struts.Xml?
The consistent tag together with name and price attributes may be used to override any of the subsequent residences described in default.Properties, like we just set struts.DevMode property. Setting struts.DevMode assets allows us to look more debug messages in the log document.
Q42. What Is The Purpose Of Struct-config.Xml In Struct2?
The struts-config.Xml configuration document is a hyperlink between the View and Model components within the Web Client.
Q43. What Is The Purpose Of
This is a marker annotation for kind conversions at Type stage. The Conversion annotation have to be applied at Type degree.
@Conversion()
public magnificence ConversionAction implements Action
Q44. Which Interceptor Is Responsible For Mapping Request Parameters To Action Class Java Bean Properties?
Com.Opensymphony.Xwork2.Interceptor.ParametersInterceptor interceptor is chargeable for mapping request parameters to the Action elegance java bean properties. This interceptor is configured in struts-default bundle with call “params”. This interceptor is a part of basicStack and defaultStack interceptors stack.
Q45. What Is The Purpose Of
This validation annotation assessments that a subject is a valid email deal with if it includes a non-empty String.
Public class Employee extends ActionSupport
@EmailValidator(message = "Default message",
key = "i18n.Key", shortCircuit = proper)
public String getEmail()
return electronic mail;
Q46. What Is Internationalization?
Internationalization (i18n) is the process of planning and enforcing products and services that allows you to without problems be tailored to particular neighborhood languages and cultures, a process referred to as localization. The internationalization process is every now and then known as trlation or localization enablement.
Q47. What Is Valuestack And Ognl?
ValueStack is the garage place where the utility facts is stored by Struts2 for processing the patron requests. The information is stored in ActionContext objects 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 manipulate information stored at the ValueStack. As you can see in structure diagram, each interceptors and end result pages can get entry to information stored on ValueStack the usage of OGNL.
Q48. What Are The Benefits Of Interceptors In Struts2?
Some of the advantages of interceptors are:
Interceptor performs a crucial position in attaining high degree of separation of worries.
Struts2 interceptors are configurable, we are able to configure it for any movement we need.
We can create our own custom interceptors to perform some commonplace responsibilities which include request params logging, authentication and many others. This enables us in looking after commonplace duties at a single vicinity, achieving low upkeep fee.
We can create interceptors stack to use with extraordinary moves.
Q49. What Is The Purpose Of
This is used to enhance the execute() approach. The Action approach also takes in a fee which is the URL on which the movement is invoked.
Public elegance Employee extends ActionSupport
private String name;
non-public int age;
@Action(price="/empinfo")
public String execute()
return SUCCESS;
Q50. What Is The Purpose Of Global-forwards Tag In Struct-config.Xml?
This section maps a page in your webapp to a call. You can use this name to consult the real page. This avoids hardcoding URLs for your internet pages.

