Apache Struts 2 Interview Questions & Answers

5 avg. rating (100% score) - 1 votes

Apache Struts 2 Interview Questions & Answers

Searching for Apache Struts 2 job? Need interview questions to prepare well for the job interview. Then you are at the right place. Apache Struts 2 jobs are available in many companies. Top companies are hiring for Apache Struts 2 roles for various positions. Apache Struts 2 is an open-source web application framework for developing Java EE web applications. The leading companies that offer various job positions like Senior Software Developer, Senior Java Software Developer, Lead software developer, Core java developer spring/struts, Engineering manager, j2eE programmer, Application developer and many more. You can get your dream job by good practice. We have provided a detailed amount of Apache Struts 2 job interview questions and answers on this page. So, visit our website wisdomjobs.com for more interview questions and answers.

Apache Struts 2 Interview Questions

Apache Struts 2 Interview Questions
    1. Question 1. What Is Struts2?

      Answer :

      Struts2 is popular and mature web application framework based on the MVC design pattern. Struts2 is not just the next version of Struts 1, but it is a complete rewrite of the Struts architecture.

    2. Question 2. Name Some Of The Features Of Struts2?

      Answer :

      Here are some of the great features that may force you to consider Struts2 −

      POJO forms and POJO actions − Struts2 has done away with the Action Forms that were an integral part of the Struts framework. With Struts2, you can use any POJO to receive the form input. Similarly, you can now see any POJO as an Action class.

      Tag support − Struts2 has improved the form tags and the new tags allow the developers to write less code.

      AJAX support − Struts2 has recognised the take over by Web2.0 technologies, and has integrated AJAX support into the product by creating AJAX tags, that function very similar to the standard Struts2 tags.

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

      Template Support − Support for generating views using templates.

      Plugin Support − The core Struts2 behaviour can be enhanced and augmented by the use of plugins. A number of plugins are available for Struts2.

    3. Question 3. What Are The Core Components Of A Struct2 Based Application?

      Answer :

      The Model-View-Controller pattern in Struts2 is realized with following five core components −

      • Actions
      • Interceptors
      • Value Stack / OGNL
      • Results / Result types
      • View technologies

    4. Question 4. Explain The Life Cycle Of A Request In Struct2 Application?

      Answer :

      Following is the life cycle of a request in Struct2 application −

      • User sends a request to the server for requesting for some resource (i.e pages).
      • The FilterDispatcher looks at the request and then determines the appropriate Action.
      • Configured interceptors functionalities applies such as validation, file upload etc.
      • Selected action is executed to perform the requested operation.
      • Again, configured interceptors are applied to do any post-processing if required.
      • Finally the result is prepared by the view and returns the result to the user.

    5. Question 5. What Is The Purpose Of Struts.xml In Struct2?

      Answer :

      The struts.xml file contains the configuration information that you will be modifying as actions are developed. This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes.

    6. Question 6. What Is The Purpose Of Constant Tag In Struts.xml?

      Answer :

      The constant tag along with name and value attributes will be used to override any of the following properties defined in default.properties, like we just set struts.devMode property. Setting struts.devMode property allows us to see more debug messages in the log file.

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

      Answer :

      We define action tags corresponds to every URL we want to access and we define a class with execute() method which will be accessed whenever we will access corresponding URL.

      Results determine what gets returned to the browser after an action is executed. The string returned from the action should be the name of a result. Results are configured per-action as above, or as a "global" result, available to every action in a package. Results have optional name and type attributes. The default name value is "success".

    8. Question 8. What Is The Purpose Of Struct-config.xml In Struct2?

      Answer :

      The struts-config.xml configuration file is a link between the View and Model components in the Web Client.

    9. 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 name. You use this name as an alias for your ActionForm throughout the rest of the struts-config.xml file, and even on your JSP pages.

    10. Question 10. What Is The Purpose Of Global-forwards Tag In Struct-config.xml?

      Answer :

      This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This avoids hardcoding URLs on your web pages.

    11. Question 11. What Is The Purpose Of Action-mappings Tag In Struct-config.xml?

      Answer :

      This is where you declare form handlers and they are also known as action mappings.

    12. Question 12. What Is The Purpose Of Plug-in Tag In Struct-config.xml?

      Answer :

      This section tells Struts where to find your properties files, which contain prompts and error messages.

    13. Question 13. What Is The Purpose Of Struts.properties In Struct2?

      Answer :

      This configuration file provides a mechanism to change the default behavior of the framework. Actually all of the properties contained within the struts.properties configuration file can also be configured in the web.xml using the init-param, as well using the constant tag in the struts.xml configuration file. But if you like to keep the things separate and more struts specific then you can create this file under the folder WEB-INF/classes. The values configured in this file will override the default values configured in default.properties which is contained in the struts2-core-x.y.z.jar distribution.

    14. Question 14. What Are Interceptors In Struts 2?

      Answer :

      Interceptors are conceptually the same as servlet filters or the JDKs Proxy class. Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework.

      You can achieve the following using interceptors :

      • Providing preprocessing logic before the action is called.
      • Providing postprocessing logic after the action is called.
      • Catching exceptions so that alternate processing can be performed.

    15. Question 15. How Can You Create Your Custom Interceptor In Struts 2?

      Answer :

      Creating a custom interceptor is easy; the interface that needs to be extended is the Interceptor interface.

    16. Question 16. How Interceptor Works In Struts 2?

      Answer :

      • Actual action will be executed using the interceptor by invocation.invoke() call. So you can do some pre-processing and some post-processing based on your requirement.
      • The framework itself starts the process by making the first call to the ActionInvocation object's invoke(). Each time invoke() is called, ActionInvocation consults its state and executes whichever interceptor comes next. When all of the configured interceptors have been invoked, the invoke() method will cause the action itself to be executed.

    17. Question 17. What Are Result Types In Struts?

      Answer :

      The Action class manages the application's state, and the Result Type manages the view.

    18. Question 18. What Is Defeult Result Type?

      Answer :

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

    19. Question 19. What Is The Purpose Of Dispatcher Result Type?

      Answer :

      The dispatcher result type is the default type, and is used if no other result type is specified. It's used to forward to a servlet, JSP, HTML page, and so on, on the server. It uses the RequestDispatcher.forward() method.

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

      Answer :

      The redirect result type calls the standard response.sendRedirect() method, causing the browser to create a new request to the given location. We can provide the location either in the body of the <result...> element or as a <param name="location"> element.

    21. Question 21. What Is Value Stack?

      Answer :

      The value stack is a set of several objects which keeps the following objects in the provided order −

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

      The Model Object − If you are using model objects in your struts application, the current model object is placed before the action on the value stack.

      The Action Object − This will be the current action object which is being executed.

      Named Objects − These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes.

    22. Question 22. What Is Ognl?

      Answer :

      The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.

    23. Question 23. Which Components Are Available Using Actioncontext Map?

      Answer :

      The ActionContext map consists of the following −

      application − application scoped variables.

      session − session scoped variables.

      root / value stack − all your action variables are stored here.

      request − request scoped variables.

      parameters − request parameters.

      atributes − the attributes stored in page, request, session and application scope.

    24. Question 24. Which Interceptor Is Responsible For File Upload Support?

      Answer :

      File uploading in Struts is possible through a pre-defined interceptor called FileUpload interceptor which is available through the org.apache.struts2.interceptor.FileUploadInterceptor class and included as part of the defaultStack.

    25. Question 25. What Are The Struts2 Configuration Properties That Control File Uploading Process?

      Answer :

      Following are the Struts2 configuration properties that control file uploading process −

      struts.multipart.maxSize − The maximum size (in bytes) of a file to be accepted as a file upload. Default is 250M.

      struts.multipart.parser − The library used to upload the multipart form. By default is jakarta.

      struts.multipart.saveDir − The location to store the temporary file. By default is javax.servlet.context.tempdir.

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

      Answer :

      The fileUplaod interceptor uses several default error message keys −

      struts.messages.error.uploading − A general error that occurs when the file could not be uploaded.

      struts.messages.error.file.too.large − Occurs when the uploaded file is too large as specified by maximumSize.

      struts.messages.error.content.type.not.allowed − Occurs when the uploaded file does not match the expected content types specified.

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

      Answer :

      You can override the text of these messages in WebContent/WEB-INF/classes/messages.properties resource files.

    28. Question 28. What Is Structs 2 Validation Framework?

      Answer :

      At Struts's core, we have the validation framework that assists the application to run the rules to perform validation before the action method is executed. Action class should extend the ActionSupport class, in order to get the validate method executed.

    29. Question 29. How Struts 2 Validation Works?

      Answer :

      • When the user presses the submit button, Struts 2 will automatically execute the validate method and if any of the if statements listed inside the method are true, Struts 2 will call its addFieldError method. If any errors have been added then Struts 2 will not proceed to call the execute method. Rather the Struts 2 framework will return input as the result of calling the action.
      • So when validation fails and Struts 2 returns input, the Struts 2 framework will redisplay the view file. Since we used Struts 2 form tags, Struts 2 will automatically add the error messages just above the form filed.
      • These error messages are the ones we specified in the addFieldError method call. The addFieldError method takes two arguments. The first is the form field name to which the error applies and the second is the error message to display above that form field.

    30. Question 30. What Is Xml Based Validation In Struts2?

      Answer :

      The second method of doing validation is by placing an xml file next to the action class. Struts2 XML based validation provides more options of validation like email validation, integer range validation, form validation field, expression validation, regex validation, required validation, requiredstring validation, stringlength validation and etc.

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

      Answer :

      The xml file needs to be named '[action-class]'-validation.xml.

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

      Answer :

      Following is the list of various types of field level and non-field level validation available in Struts2 −

      • date validator
      • double validator
      • email validator
      • expression validator
      • int validator
      • regex validator
      • required validator
      • requiredstring validator
      • stringlength validator
      • url validator

    33. Question 33. What Is Internationalization?

      Answer :

      Internationalization (i18n) is the process of planning and implementing products and services so that they can easily be adapted to specific local languages and cultures, a process called localization. The internationalization process is sometimes called translation or localization enablement.

    34. Question 34. How Struts2 Supports Internationalization?

      Answer :

      Struts2 provides localization ie. internationalization (i18n) support through resource bundles, interceptors and tag libraries in the following places −

      • The UI Tags.
      • Messages and Errors.
      • Within action classes.

    35. Question 35. What Is The Naming Convention For A Resource Bundle File In Struts2?

      Answer :

      The simplest naming format for a resource file is −

      bundlename_language_country.properties

      Here bundlename could be ActionClass, Interface, SuperClass, Model, Package, Global resource properties. Next part language_country represents the country locale for example Spanish (Spain) locale is represented by es_ES and English (United States) locale is represented by en_US etc. Here you can skip country part which is optional.

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

      Answer :

      When you reference a message element by its key, Struts framework searches for a corresponding message bundle in the following order −

      • ActionClass.properties
      • Interface.properties
      • SuperClass.properties
      • model.properties
      • package.properties
      • struts.properties
      • global.properties

    37. Question 37. Which Class Of Struts Is Responsible To Converts Data Types From String And Vice Versa?

      Answer :

      StrutsTypeConverter class tells Struts how to convert Environment to a String and vice versa by overriding two methods convertFromString() and convertToString().

    38. Question 38. What Inbuilt Themes Are Provided By Struts2?

      Answer :

      Struts 2 comes with three built-in themes −

      simple theme − A minimal theme with no "bells and whistles". For example, the textfield tag renders the HTML <input/> tag without a label, validation, error reporting, or any other formatting or functionality.

      xhtml theme − This is the default theme used by Struts 2 and provides all the basics that the simple theme provides and adds several features like standard two-column table layout for the HTML, Labels for each of the HTML, Validation and error reporting etc.

      css_xhtml theme − This theme provides all the basics that the simple theme provides and adds several features like standard two-column CSS-based layout, using <div> for the HTML Struts Tags, Labels for each of the HTML Struts Tags, placed according to the CSS stylesheet.

    39. Question 39. How To Handle Exceptions In Structs?

      Answer :

      Struts makes the exception handling easy by the use of the "exception" interceptor. The "exception" interceptor is included as part of the default stack, so you don't have to do anything extra to configure it. It is available out-of-the-box ready for you to use.

    40. Question 40. What Is The Purpose Of @results Annotation?

      Answer :

      A @Results annotation is a collection of results. Under the @Results annotation, we can have multiple @Result annotations.

      @Results({

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

         @Result(name="error", value="/error.jsp")

      })

      public class Employee extends ActionSupport{

       ...

      }

    41. Question 41. What Is The Purpose Of @result Annotation?

      Answer :

      The @result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from execute().

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

      public class Employee extends ActionSupport{

       ...

      }

    42. Question 42. What Is The Purpose Of @action Annotation?

      Answer :

      This is used to decorate the execute() method. The Action method also takes in a value which is the URL on which the action is invoked.

      public class Employee extends ActionSupport{

         private String name;

         private int age;

         @Action(value="/empinfo")

         public String execute() 

         {

             return SUCCESS;

         }

      }

    43. Question 43. What Is The Purpose Of @after Annotation?

      Answer :

      The @After annotation marks a action method that needs to be called after the main action method and the result was executed. Return value is ignored.

      public class Employee extends ActionSupport{

         @After

         public void isValid() throws ValidationException {

            // validate model object, throw exception if failed

         }

         public String execute() {

            // perform secure action

            return SUCCESS;

         }

      }

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

      Answer :

      The @Before annotation marks a action method that needs to be called before the main action method and the result was executed. Return value is ignored.

      public class Employee extends ActionSupport{

         @Before

         public void isAuthorized() throws AuthenticationException {

            // authorize request, throw exception if failed

         }

         public String execute() {

            // perform secure action

            return SUCCESS;

         }

      }

    45. Question 45. What Is The Purpose Of @beforeresult Annotation?

      Answer :

      The @BeforeResult annotation marks a action method that needs to be executed before the result. Return value is ignored.

      public class Employee extends ActionSupport{

         @BeforeResult

         public void isValid() throws ValidationException {

          // validate model object, throw exception if failed

         }

         public String execute() {

            // perform action

            return SUCCESS;

         }

      }

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

      Answer :

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

      public class Employee extends ActionSupport{

         @ConversionErrorFieldValidator(message = "Default message", 

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

         public String getName() {

             return name;

         }

      }

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

      Answer :

      his validation annotation checks that a double field has a value within a specified range. If neither min nor max is set, nothing will be done.

      public class Employee extends ActionSupport{

         @DoubleRangeFieldValidator(message = "Default message", 

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

         minInclusive = "0.123", maxInclusive = "99.987")

         public String getIncome() {

             return income;

         }

      }

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

      Answer :

      This validation annotation checks that a field is a valid e-mail address if it contains a non-empty String.

      public class Employee extends ActionSupport{

         @EmailValidator(message = "Default message", 

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

         public String getEmail() {

             return email;

         }

      }

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

      Answer :

      This non-field level validator validates a supplied regular expression.

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

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

      Answer :

      This validation annotation checks that a numeric field has a value within a specified range. If neither min nor max is set, nothing will be done.

      public class Employee extends ActionSupport{

         @IntRangeFieldValidator(message = "Default message", 

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

         min = "0", max = "42")

         public String getAge() {

             return age;

         }

      }

    51. Question 51. What Is The Purpose Of @requiredstringvalidator Annotation?

      Answer :

      This validation annotation checks that a String field is not empty (i.e. non-null with a length > 0).

      public class Employee extends ActionSupport{

         @RequiredStringValidator(message = "Default message", 

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

         public String getName() {

             return name;

         }

      }

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

      Answer :

      This validator checks that a String field is of the right length. It assumes that the field is a String. If neither minLength nor maxLength is set, nothing will be done.

      public class Employee extends ActionSupport{

         @StringLengthFieldValidator(message = "Default message", 

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

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

         public String getName() {

             return name;

         }

      }

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

      Answer :

      This validator checks that a field is a valid URL.

      public class Employee extends ActionSupport{

         @UrlValidator(message = "Default message", 

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

         public String getURL() {

             return url;

         }

      }

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

      Answer :

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

      public class Employee extends ActionSupport{

        @Validations(

         requiredFields =

            {@RequiredFieldValidator(type = ValidatorType.SIMPLE, 

            fieldName = "customfield", 

            message = "You must enter a value for field.")},

         requiredStrings =

            {@RequiredStringValidator(type = ValidatorType.SIMPLE, 

            fieldName = "stringisrequired", 

            message = "You must enter a value for string.")}

         )

         public String getName() {

             return name;

         }

      }

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

      Answer :

      This annotation can be used for custom validators. Use the ValidationParameter annotation to supply additional params.

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

    56. 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 must be applied at Type level.

      @Conversion()

         public class ConversionAction implements Action {

      }

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

      Answer :

      This annotation sets the CreateIfNull for type conversion. The CreateIfNull annotation must be applied at field or method level.

      @CreateIfNull( value = true )

      private List<User> users;

    58. Question 58. What Is The Purpose Of @element Annotation Annotation?

      Answer :

      This annotation sets the Element for type conversion. The Element annotation must be applied at field or method level.

      @Element( value = com.acme.User )

      private List<User> userList;

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

      Answer :

      This annotation sets the Key for type conversion. The Key annotation must be applied at field or method level.

      @Key( value = java.lang.Long.class )

      private Map<Long, User> userMap;

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

      Answer :

      This annotation sets the KeyProperty for type conversion. The KeyProperty annotation must be applied at field or method level.

      @KeyProperty( value = "userName" )

      protected List<User> users = null;

    61. Question 61. What Is The Purpose Of @typeconversion Annotation Annotation?

      Answer :

      This annotation annotation is used for class and application wide conversion rules. The TypeConversion annotation can be applied at property and method level.

      @TypeConversion(rule = ConversionRule.COLLECTION, 

      converter = "java.util.String")

      public void setUsers( List users ) {

         this.users = users;

      }

    62. Question 62. What Are Struts2 Core Components?

      Answer :

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

    63. Question 63. Which Interceptor Is Responsible For I18n Support?

      Answer :

      com.opensymphony.xwork2.interceptor.I18nInterceptor interceptor is responsible for i18n support in Struts2 applications. This interceptor is configured in struts-default package with name “i18n” and it’s part of i18nStack and defaultStack.

    64. 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 implement Action interface to create our action classes. This interface has a single method execute() that we need to implement. The only benefit of using this interface is that it contains some constants that we can use for result pages, these constants are SUCCESS, ERROR, NONE, INPUT and LOGIN. 

      ActionSupport class is the default implementation of Action interface and it also implements interfaces related to Validation and i18n support. ActionSupport class implements Action, Validateable, ValidationAware, TextProvider and LocaleProvider interfaces. We can override validate() method of ActionSupport class to include field level validation login in our action classes. 

      Depending on the requirements, we can use any of the approaches to create struts 2 action classes, my favorite is ActionSupport class because it helps in writing validation and i18n logic easily in action classes.

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

      Answer :

      Struts2 action classes doesn’t provide direct access to Servlet API components such as Request, Response and Session. However sometimes we need these access in action classes such as checking HTTP method or setting cookies in response. 

      That's why Struts2 API provides a bunch of *Aware interfaces that we can implement to access these objects. Struts2 API uses dependency injection to inject Servlet API components in action classes. Some of the important Aware interfaces are SessionAware, ApplicationAware, ServletRequestAware and ServletResponseAware.

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

      Answer :

      Struts2 provide different ways to create action classes. 

      • By implementing Action interface
      • Using Struts2 @Action annotation
      • By extending ActionSupport class
      • Any normal java class with execute() method returning String can be configured as Action class.

    67. Question 67. What Is The Use Of Execandwait Interceptor?

      Answer :

      Struts2 provides execAndWait interceptor for long running action classes. We can use this interceptor to return an intermediate response page to the client and once the processing is finished, final response is returned to the client. This interceptor is defined in the struts-default package and implementation is present in ExecuteAndWaitInterceptor class.

    68. Question 68. Does Struts2 Action And Interceptors Are Thread Safe?

      Answer :

      • Struts2 Action classes are thread safe because an object is instantiated for every request to handle it. 
      • Struts2 interceptors are singleton classes and a new thread is created to handle the request, so it’s not thread safe and we need to implement them carefully to avoid any issues with shared data.

    69. Question 69. What Is The Use Of Token Interceptor In Struts2?

      Answer :

      One of the major problems with web applications is the double form submission. If not taken care, double form submission could result in charging double amount to customer or updating database values twice. We can use token interceptor to solve the double form submission problem. This interceptor is defined in struts-default package but it’s not part of any interceptor stack, so we need to include it manually in our action classes.

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

      Answer :

      Struts2 provides easy integration of log4j API for logging purpose, all we need to have is log4j configuration file in the WEB-INF/classes directory.

    71. Question 71. Which Class Is The Front Controller In Struts2?

      Answer :

      org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter is the Front Controller class in Struts2 and every request processing starts from this class. Earlier versions of Struts2 uses org.apache.struts2.dispatcher.FilterDispatcher as Front Controller class

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

      Answer :

      Struts2 provides a lot of custom tags that we can use in result pages to create views for client request. These tags are broadly divided into three categories- Data tags, Control tags and UI tags. 

      We can use these tags by adding these in JSP pages using taglib directive.

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

    73. Question 73. What Is Custom Type Converter In Struts2?

      Answer :

      Struts2 support OGNL expression language and it performs two important tasks in Struts 2 – data transfer and type conversion. 

      OGNL is flexible and we can easily extend it to create our own custom converter class. Creating and configuring custom type converter class is very easy, first step is to fix the input format for the custom class. Second step is to implement the converter class. Type converter classes should implement com.opensymphony.xwork2.conversion.TypeConverter interface. Since in web application, we always get the request in form of String and send response in the form of String, Struts 2 API provides a default implementation of TypeConverter interface, StrutsTypeConverter. StrutsTypeConverter contains two abstract methods – convertFromString to convert String to Object and convertToString to convert Object to String.

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

      Answer :

      Some of the benefits of interceptors are: 

      • Interceptor plays a crucial role in achieving high level of separation of concerns.
      • Struts2 interceptors are configurable, we can configure it for any action we want.
      • We can create our own custom interceptors to perform some common tasks such as request params logging, authentication etc. This helps us in taking care of common tasks at a single location, achieving low maintenance cost.
      • We can create interceptors stack to use with different actions.

    75. Question 75. What Is Valuestack And Ognl?

      Answer :

      ValueStack is the storage area where the application data is stored by Struts2 for processing the client requests. The data is stored in ActionContext objects that use ThreadLocal to have values specific to the particular request thread. 

      Object-Graph Navigation Language (OGNL) is a powerful Expression Language that is used to manipulate data stored on the ValueStack. As you can see in architecture diagram, both interceptors and result pages can access data stored on ValueStack using OGNL.

    76. Question 76. What Is Life Cycle Of An Interceptor?

      Answer :

      Interceptor interface defines three methods – init(), destroy() and intercept(). init and destroy are the life cycle methods of an interceptor. Interceptors are Singleton classes and Struts2 initialize a new thread to handle each request. init() method is called when interceptor instance is created and we can initialize any resources in this method. destroy() method is called when application is shutting down and we can release any resources in this method. 

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

      Answer :

      struts-default is an abstract package that defines all the Struts2 interceptors and commonly used interceptor stack. It is advisable to extend this package while configuring our application package to avoid configuring interceptors again. This is provided to help developers by eliminating the trivial task of configuring interceptor and result pages in our application.

    78. Question 78. Name Some Useful Annotations Introduced In Struts2?

      Answer :

      Some of the important annotations introduced in Struts2 are: 

      • @Action to create action class
      • @Actions to configure single class for multiple actions
      • @Namespace and @Namespaces for creating different modules
      • @Result for result pages
      • @ResultPath for configuring result pages location

    79. Question 79. What Is An Interceptor Stack?

      Answer :

      An interceptor stack helps us to group together multiple interceptors in a package for further use. struts-default package creates some of the mostly used interceptor stack – basicStack and defaultStack. We can create our own interceptor stack at the start of the package and then configure our action classes to use it.

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

      Answer :

      The default URI suffix for Struts2 action is .action, in Struts1 default suffix was .do. We can change this suffix by defining struts.action.extension constant value in our Struts2 configuration file as:

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

    81. Question 81. 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 application in development mode. This mode does reload properties files and provides extra logging and debugging feature. It’s very useful while developing our application but we should turn it off while moving our code to production. 
      • struts.convention.result.path to configure the location of result pages. By default Struts2 look for result pages at {WEBAPP-ROOT}/{Namespace}/ and we can change the location with this constant. 
      • struts.custom.i18n.resources to define global resource bundle for i18n support. 
      • struts.action.extension to configure the URL suffix to for Struts2 application. Default suffix is .action but sometimes we might want to change it to . do or something else. 

      We can configure above constants in struts.xml file like below. 

      < 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 >

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

      Answer :

      File Upload is one of the common task in a web application. Thats why Struts2 provides built in support for file upload through FileUploadInterceptor. This interceptor is configured in struts-default package and provide options to set the maximum size of a file and file types that can be uploaded to the server.

    83. 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 separate our action classes based on their functionality, for example admin, user, customer etc.

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

      Answer :

      com.opensymphony.xwork2.interceptor.ParametersInterceptor interceptor is responsible for mapping request parameters to the Action class java bean properties. This interceptor is configured in struts-default package with name “params”. This interceptor is part of basicStack and defaultStack interceptors stack.

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

      Answer :

      Some of the best practices while developing Struts2 application are: 

      • Always try to extend struts-default package while creating your package to avoid code redundancy in configuring interceptors. 
      • For common tasks across the application, such as logging request params, try to use interceptors. 
      • Always keep action classes java bean properties in a separate bean for code reuse and implement ModelDriven interface. 
      • If you have custom interceptor that you will use in multiple actions, create interceptor stack for that and then use it. 
      • Try to divide your application in different modules with namespace configuration based on functional areas. 
      • Try to use Struts2 tags in result pages for code clarify, if needed create your own type converters. 
      • Use development mode for faster development, however make sure production code doesn’t run in dev mode. 
      • Use Struts2 i18n support for resource bundles and to support localization. 
      • Struts2 provides a lot of places where you can have resource bundles but try to keep one global resource bundle and one for action class to avoid confusion. 
      • struts-default package configures all the interceptors and creates different interceptor stacks. Try to use only what is needed, for example if you don’t have localization requirement, you can avoid i18n interceptor.

    86. Question 86. What Is The Default Location Of Result Pages And How Can We Change It?

      Answer :

      By default Struts2 looks for result pages in {WEBAPP-ROOT}/{Namespace}/ directory but sometimes we want to keep result pages in another location, we can provide struts.convention.result.path constant value in Struts2 configuration file to change the result pages location. 

      Another way is to use @ResultPath annotation in action classes to provide the result pages location.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Apache Struts 2 Tutorial