ContactUs

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

What is ActionMapping Class in Struts ?

ActionMappings is a collection of ActionMapping objects

The ActionMapping contains the knowledge of how a specific event maps to specific Actions.

The ActionServlet (Command) passes the ActionMapping to the Action class via the perform() method.

This allows Action to access the information to control flow.

The struts-config.xml determines what Action class the Controller calls.

The struts-config.xml configuration information is translated into a set of ActionMapping, which are put into container of ActionMappings.

Classes that end with s are containers.

What are the Validator Built-in Rules in Struts ?

required : field data provided

minlength : more than min length

maxlength : less than max length

range : in range of values

mask : correct format (takes regexp)

date : validates correct date format

email : validates correct E-Mail fromat

primitives: byte, integer, float, double, etc.

How to prevent multi-click using struts tokens ?

Mutli-click prevention using struts tokens- Prevent Duplicate Submission :

saveToken() : generate the token key and save to request/session attribute.

isTokenValid() : validate submitted token key against the 1 store in request/session.

resetToken() : reset the token key

 

Follow the steps to setup Mutli-click prevention using struts tokens.

 

Step 1: Action Class where saveToken() before JSP Page

 

First saveToken() then forward to your jsp.

Upon loading the form, invokes saveToken() on the action class to create and store the token key.

Struts will store the generated key in request/session.

public class LoadAction extends Action

{

public ActionForward execute(ActionMapping mapping,ActionForm form,

HttpServletRequest request,HttpServletResponse response)

{ ActionForward forward;

saveToken(request);

forward=mapping.findForward("empformpage");

// this is the jsp page where you want to struts tokens.

return forward;

}

}

Step 2:Store Token key as a hidden field ( empform.jsp) 

In the browser if you type : http://localhost:8080/testApp/loadActio.do

This will call execute() method of LoadAction. Then saveToken(request);//create and store the token key and mapping.findForward("empformpage"); forward to empform.jsp (below code is for empform.jsp)

<%@ page import="org.apache.struts.action.Action"%>

<%@ page import="org.apache.struts.taglib.html.Constants"%>

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

 

 

 

Save

 

Step 3. Check Token is Valid ?

Once the form submitted, invokes isTokenValid() on the action class, it will validate the submitted token key(hidden field) with the token key stored previously on request/session. If match, it will return true.

public class SubmitAction extends Action

{

public ActionForward execute(ActionMapping mapping ,ActionForm form ,HttpServletRequest request,

HttpServletResponse response)

{

EmpForm frm=(EmpForm)form;

if(isTokenValid(request))

{ // This is Not Duplicate Submission of the form

// You can add your logic here

resetToken(request);

return mapping.findForward("sucess");

}

else

{ // This is Duplicate Submission of the form

// Return to the JSP to display the error message ( This is Duplicate Submission);

return mapping.findForward("duplicatesubmitpage");

}

}

}

 

Differences between web.xml and sturts-config.xml ?

web.xml :

It is used for the deployment descriptor for web applications

web.xml is used for making connection between web container & web application

It is read by container when we start the container.

sturts-config.xml :

It is used for deployment descripror for struts application.

It is used for making connection between view & controller

It is read by init() method of ActionServlet.

Explain life cycle of ActionForm ?

The lifecycle of ActionForm invoked by the RequestProcessor is as follows:

Retrieve or Create Form Bean associated with Action

"Store" FormBean in appropriate scope (request or session)

Reset the properties of the FormBean

Populate the properties of the FormBean

Validate the properties of the FormBean

Pass FormBean to Action

What are the different types of Actions available in Struts ?

DispatchAction:

 

One of the built-in actions provided by the struts framework. The collection of related functions into a single Action is possible using this action. It allows eliminating the creation of multiple independent actions for each function.

 

ActionDispatcher:

 

It is a helper class which dispatches to a method that is in Action. This class provides an alternative mechanism for using DispatchAction. With the help of various types of mechanisms, the ‘dispatching’ behavior can be easily implemented into an Action without inheritance of a particular super Action class.

 

LookupDispatchAction:

 

The subclass mapped execute() method is dispatched by this abstract Action class. This process is useful where a HTML form has many clicks on submit buttons with the same name. The corresponding ActionMapping’s parameter property specifies the button name.

 

Forward Action and IncludeAction:

 

These forward and include the context-relative URI specified by the parameter property of our associated ActionMapping.

What is the difference between perform() and execute() methods ?

Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet.

This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic.

As we already mentioned, to support declarative exception handling, the method signature changed in perform.

Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

Is struts threadsafe ?

Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object.

How RequestProcessor decides that validation is success or fail ?

Based on ActionErrors instance returned by Formbean java class validate().

The action form class provides a method validate() which is called before the action class is executed. So you can validate your properties within this method. The return-value of the method is a collection (ActionErrors) of error messages (ActionMessage).

What is the difference between ActionForm and DynaActionForm ?

ActionForm will populate the properties depending on the respective JSP fields.In this we can specify the validate() method (if required) for validations or else you can use ActionErrors for validating.

 

DynaActionForm has to be defined in Struts-config.xml and it may have many property fields. We can use this form for many no.of JSPs. Single dynaActionForm can serve for many number of JSPs.

How to get data from the velocity page in a action class?

We can get the values in the action classes by using data.getParameter(\"variable name defined in the velocity page\");

Explain about token feature in Struts ?

Use the Action Token methods to prevent duplicate submits:

 

There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.

saveToken(request)

on the return trip,

isTokenValid(request)

resetToken(request) 

How you will enable front-end validation based on the xml in validation.xml ?

The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code:

 

<html:javascript formName=\"logonForm\" dynamicJavascript=\"true\" staticJavascript=\"true\" />

 

generates the client side java script for the form \"logonForm\" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

How you will display validation fail errors on jsp page ?

Following tag displays all the errors:

<html:errors/>

Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

What is the difference between DynaActionForm and DynaValidatorForm?

Specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean.

 

This class extends DynaActionForm and provides basic field validation based on an XML file. The key passed into the validator is the action element's 'name' attribute from the struts-config.xml which should match the form element's name attribute in the validation.xml.

What is Struts Validator Framework ?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

 

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

What is DispatchAction ?

Basically Dispatch action is used when you have multiple submit buttons in a single form.The Dispatch action is a class which extends the Struts DispatchAction , and encpsulates all the action methods (similar to execute method in Action class)in one single class.These actions methods will get executed based on the parameter that you pass in a jsp page.In the Struts-Config.xml you need to define the DispatchAction class and the parameter name that you passing in the URL.Based on the parameter the Controller will invoke the action method.

 

struts-config.xml

parameter – attribute is used to delegate the request to corresponding method of the BookAction class. So define this value with appropriate name.

 

BookAction.java

It eliminates the execute method entirely.  Because it directly implements the desired methods, those custom methods have same signature as execute method.

The class BookAction extends org.apache.struts.actions.DispatchAction

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForward;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.actions.DispatchAction;

 

public class BookAction extends DispatchAction

{

public ActionForward addBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

System.out.println("Add Book Page");

return mapping.findForward("addBook");

}

 

public ActionForward editBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

System.out.println("Edit Book Page");

return mapping.findForward("editBook");

}

 

public ActionForward saveBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

System.out.println("Save Book Page");

return mapping.findForward("saveBook");

}

 

public ActionForward deleteBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {

System.out.println("Delete Book Page");

return mapping.findForward("deleteBook");

}

}

bookdetails.jsp

This page has four different links for doing different actions say Add/Edit/Save/Delete books. Every individual action has to be uniquely represented by the request parameter actionMethod.

 

What is IncludeAction ?

An Action that includes the context-relative URI specified by the parameter property of our associated ActionMapping. This can be used to integrate Struts with other business logic components that are implemented as servlets (or JSP pages), but still take advantage of the Struts controller servlet's functionality

 

<action name="log"

parameter="/WEB-INF/classes/com/struts/ser/ShowServlet" 

path="/logs1"

type="org.apache.struts.actions.IncludeAction">

</action>

What is ForwardAction ?

The struts framework ForwardAction class provides a mechanism for forwarding to a specified URL. In an MVC Web application, all requests to the application are supposed to flow through the Controller servlet.

 

This will ensure that the Controller layer of the application has an opportunity to prepare any resources that may be needed to handle the request meaning selecting the correct module and so on. The struts framework ForwardAction is provided as a simple utility action that can be used for scenarios in which you simply want to link to a JSP page.

 

Example:

 

<action parameter="/Welcome.jsp"

       path="/Welcome"

       type="org.apache.struts.actions.ForwardAction">

</action>

What is ActionForm ?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.
ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

How is the MVC design pattern used in Struts framework?

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

 

Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:

 

 

Model: application state

View: presentation of data (JSP, HTML)

Controller: routing of the application flow

 

1. Model Tier :

Struts includes only minimal infrastructure for the model tier

A basic implementation of javax.sql.DataSource is included

But you can integrate any desired approach

 

2. View Tier :

 Form Beans:

Represent the server side state of the input fields on an HTML form

Contains hooks for resetting fields to default values (needed for checkboxes) and input field validation

DynaActionForm means you do not have to create new JavaBeans yourself

Validation Framework:

Abstract input validation rules into separate XML document

Extensible for custom field checking

Optionally generates client-side JavaScript

Always checks on server side

Integrated with standard ActionForm beans and DynaActionForm beans

(JSP) Custom Tag Libraries:

Bean – General purpose bean and property manipulation

Html – Dynamic HTML-based user interfaces (including input forms)

Logic – Conditionals and iteration

Nested – Versions of other tags that access nested JavaBean hierarchies easily

Tiles – Layout management (next page)

(JSP) Tiles Framework:

Supports templating for common look and feel of all pages in a web app

Tile definitions created in JSP page or in external XML document

Definitions can extend base definitions

Advanced techniques for dynamically passing information to tiles

3. Controller Tier :

Configuration Document Defines Behavior

Action URLs mapped to Actions

Data sources

Exception handlers

Form beans

Forwarding URLs mapped to Pages

Message Resources for i18n

PlugIns for Lifecycle Management

One or more documents allowed

Request Processing Lifecycle :

Extract action mapping path

Select locale (if necessary)

Select action mapping to utilize

Perform role-based access checks

Server-side validation (if requested)

Invoke application Action

Forward based on application outcome

Highly customizable and extendable

Sub-Application Modules :

Logically divide single web application into multiple Struts “mini-applications”

Session state shared across all modules

Standard Action Implementations:

Forward or include other URLs

Explain Struts Workflow ?

A request comes in from a Java Server Page into the ActionServlet.

The ActionServlet having already read the struts-config.xml file, knows which form bean  relates to this JSP, and delegates work to the validate method of that form bean.

The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that need to be performed.

If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields returns back to the ActionServlet.

The ActionServlet checks the ActionErrors that were returned from the form bean’s validate method to determine if any errors have occurred. If errors have occurred, it returns to the originating JSP displaying the appropriate errors.

If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.

The Action class performs any necessary business logic, and then forwards to the next appropriate action (probablyanother JSP).

Explain about Struts Config File (struts-config.xml) ?

struts-config.xml contains three important elements used to describe actions:

<form-beans> contains FormBean definitions including name and type (classname)

<action-mapping> contains action definitions

Use an <action> element for each action defined

<global-forwards> contains your global forward definitions

What is the "global-forwards" in Struts Config File ?

Forwards are instances of the ActionForward class returned from an ActionForm's execute method.These map logical names to specific resources (typically JSPs) <forward> element has following attributes.

name: logical name of the forward used within execute() method of Action class to forward to the next resource

path: to-be-forwarded resource

redirect: redirect (true) or forward (false)

What is Action Class ?

The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method.

 

In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class.

The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

What Does ActionServlet Do ?

Performs the role of Controller

Process user requests

Determine what the user is trying to achieve according to the request

Pull data from the model (if necessary) to be given to the appropriate view, and Select the proper view to respond to the user

Delegates most of this grunt work to Action classes

Is responsible for initialization and clean up of resources.

loads the application config corresponding to the "config" init-param's in web.xml.

goes through an enumeration of all init-param elements, looking for those elements who's name starts with config/ for modules

What are the Disadvantages of Struts Framework?

Struts has a number of significant advantages over the standard servlet and JSP APIs alone, due to its complexity it has some serious drawbacks as well.

 

Bigger Learning Curve:

 

To use MVC with the standard RequestDispatcher, you need to be comfortable with the standard JSP and servlet APIs. To use MVC with Struts, you have to be comfortable with the standard JSP and servlet APIs and a large and elaborate framework that is almost equal in size to the core system. This drawback is especially significant with smaller projects, near-term deadlines, and less experienced developers; you could spend as much time learning Struts as building your actual system.

 

Worse Documentation:

 

Compared to the standard servlet and JSP APIs, Struts has fewer online resources, and many first-time users find the online Apache documentation confusing and poorly organized. There are also fewer books on Apache Struts than on standard servlets and JSP.

 

Less Transparent:

 

With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications. As a result, Struts applications are:

 

 Harder to understand

 Harder to benchmark and optimize

Rigid Approach:

 

The flip side of the benefit that Struts encourages a consistent approach to MVC is that Struts makes it difficult (but by no means impossible) to use other approaches.

 

What is ActionServlet ?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta StrutsFramework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

What is and Why Struts ?

What is Struts ?

 

Struts is an open source Web application framework developed as Apache Jakarta project.

Struts is an implementation of Model-View-Controller (MVC) framework

Used for constructing web applications

using Servlets and JSPs

Pattern oriented- Singleton, composition, delegate

Easy to use and learn

Includes JSP custom tag libraries

 

Why Struts ?

 

Takes much of the complexity out of building your own MVC framework

Encourages good design practice and modeling

Easy to learn and use

Feature-rich

Many supported 3rd-party tools

Flexible and extensible

Large user community

Stable and mature

Open source   

Is Struts compatible with other Java technologies ?

Yes. Struts is committed to supporting industry standards. Struts acts as an integrator of Java technologies so that they can be used in the "real world".

What does Controller do ?

Is the switch board of MVC architecture

Every request goes through the controller

Responsible for flow control (action mapping) of the request handling

reads configuration file to determine the flow control

Dispatch to one of several methods in an Action class

Switch from one sub-application module to another

Why is Struts so Useful ?

structural separation of data presentation and business logic

easy separation of development tasks (web design, database, …)

increases maintainability and extendibility (new views!)

increases reusability of code

Struts provides a Controller that manages the control flow

changes in the flow can all be done in struts-config.xml

abstraction from (hard coded) filenames (forwards)

easy localization (internationalization is more important than ever)

based on standard Java technologies (JSP, Servlets, JavaBeans)

thus running on all kinds of JSP/Servlet containers

open-source

affordable

no dependence on external companies

robustness (due to freely accessible source code)

open-source project with growing developer community

What are the components of Struts Framework?

 Struts framework is comprised of following components:

Java Servlets

JSP (Java Server Pages)

Custom Tags

Message Resources

What's the role of a handler in MVC based applications?

It’s the job of handlers to transfer the requests to appropriate models as they are bound to the model layer of MVC architecture. Handlers use mapping information from configuration files for request transfer.

What's the flow of requests in Struts based applications?

Ans: Struts based applications use MVC design pattern. The flow of requests is as follows:

User interacts with View by clicking any link or by submitting any form.

Upon user’s interaction, the request is passed towards the controller.

Controller is responsible for passing the request to appropriate action.

Action is responsible for calling a function in Model which has all business logic implemented.

Response from the model layer is received back by the action which then passes it towards the view where user is able to see the response.

Which file is used by controller to get mapping information for request routing?

Controller uses a configuration file “struts-config.xml file to get all mapping information to decide which action to use for routing of user’s request.

What's the role of Action Class in Struts?

In Struts, Action Class acts as a controller and performs following key tasks:

After receiving user request, it processes the user’s request.

Uses appropriate model and pulls data from model (if required).

Selects proper view to show the response to the user.

How an actionForm bean is created?

actionForm bean is created by extending the class org.apache.struts.action.ActionForm

In the following example we have created an actionForm bean with the name 'testForm':

[java]

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;

public class testForm extends ActionForm

{

private String Id=null;

private String State=null;

public void setId(String id){

this.Id=id;

}

public String getId(){

return this.Id;

}

public void setState(String state){

this.State=state;

}

public String getState(){

return this.State;

}

[/java]

What are the two types of validations supported by Validator FrameWork?

Validator Framework is used for form data validation. This framework provides two types of validations:

Client Side validation on user’s browser

Server side validation

What are the steps of Struts Installation?

In order to use Struts framework, we only need to add Struts.Jar file in our development environment. Once jar file is available in the CLASSPATH, we can use the framework and develop Strut based applications.

How client side validation is enabled on a JSP form?

In order to enable client side validation in Struts, first we need to enable validator plug-in in struts-config.xml file. This is done by adding following configuration entries in this file:

[xml]

<!–  Validator plugin –>

<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>

<set-property

property=”pathnames”

value=”/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml”/>

</plug-in>

[/xml]

Then Validation rules are defined in validation.xml file. If a form contains email field and we want to enable client side validation for this field, following code is added in validation.xml file:

[xml]

<form name=”testForm”>

<field  property=”email”

depends=”required”>

<arg key=”testForm.email”/>

</field>

</form>

[/xml]

How action-mapping tag is used for request forwarding in Struts configuration file?

In Struts configuration file (struts-config.xml), forwarding options are defined under action-mapping tag.

In the following example, when a user will click on the hyperlink test.do, request will be forwarded to /pages/testing.jsp using following configurations from struts-config.xml file:

[xml]

<action  path=”/test” forward=”/pages/testing.jsp”>

[/xml]

This forwarding will take place when user will click on following hyperlink on the jsp page:

[xml]

<html:link</strong> page=”/test.do</strong>”>Controller Example</html:link>

[/xml]

How duplicate form submission can be controlled in Struts?

In Struts, action class provides two important methods which can be used to avoid duplicate form submissions.

saveToken() method of action class generates a unique token and saves it in the user’s session. isTokenValid() method is used then used to check uniqueness of tokens.

In Struts, how can we access Java beans and their properties?

Bean Tag Library is a Struts library which can be used for accessing Java beans.

Which configuration file is used for storing JSP configuration information in Struts?

For JSP configuration details, Web.xml file is used.

What's the purpose of Execute method of action class?

Execute method of action class is responsible for execution of business logic. If any processing is required on the user’s request, it’s performed in this method. This method returns actionForward object which routes the application to appropriate page.

In the following example, execute method will return an object of actionForward defined in struts-config.xml with the name “exampleAction”:

[java]

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

public class actionExample extends Action

{

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception{

return mapping.findForward(“exampleAction”);

}

}

[/java]

What's the difference between validation.xml and validator-rules.xml files in Struts Validation framework?

In Validation.xml, we define validation rules for any specific Java bean while in validator-rules.xml file, standard and generic validation rules are defined.

How can we display all validation errors to user on JSP page?

To display all validation errors based on the validation rules defined in validation.xml file, we use <html:errors /> tag in our JSP file.

What's declarative exception handling in Struts?

When logic for exception handling is defined in struts-config.xml or within the action tag, it’s known as declarative exception handling in Struts.

In the following example, we have defined exception in struts-config.xml file for NullPointerException:

[xml]

<global-exceptions>

<exception key=”test.key”

Type=”java.lang.NullPointerException”

Path=”/WEB-INF/errors/error_page.jsp”

</global-exceptions>

[/xml]

What's DynaActionForm?

DynaActionForm is a special type of actionForm class (sub-class of ActionForm Class) that’s used for dynamically creating form beans. It uses configuration files for form bean creation.

What configuration changes are required to use Tiles in Struts?

To create reusable components with Tiles framework, we need to add following plugin definition code in struts-config.xml file:

[xml]

<plug-in className=”org.apache.struts.tiles.TilesPlugin” >

<set-property property=”definitions-config” value=”/WEB-INF/tiles-defs.xml” />

<set-property property=”moduleAware” value=”true” />

</plug-in>

[/xml]

What's the difference between Jakarta Struts and Apache Struts? Which one is better to use?

Both are same and there is no difference between them.

What's the use of Struts.xml configuration file?

Struts.xml file is one the key configuration files of Struts framework which is used to define mapping between URL and action. When a user’s request is received by the controller, controller uses mapping information from this file to select appropriate action class.

How tag libraries are defined in Struts?

Tag libraries are defined in the configuration file (web.xml) inside <taglib> tag as follows:

[xml]

<taglib>

<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>

<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

</taglib>

[/xml]

What's the significance of logic tags in Struts?

Use of logic tags in Struts helps in writing a clean and efficient code at presentation layer without use of scriptlets.

What are the two scope types for formbeans?

1. Request Scope: Formbean values are available in the current request only

2. Session Scope: Formbean values are available for all requests in the current session.

How can we group related actions in one group in Struts?

To group multiple related actions in one group, we can use DispatcherAction class.

When should we use SwtichAction?

The best scenario to use SwitchAction class is when we have a modular application with multiple modules working separately. Using SwitchAction class we can switch from a resource in one module to another resource in some different module of the application.

What are the benefits of Struts framework?

Struts is based on MVC and hence there is a good separation of different layers in Struts which makes Struts applications development and customization easy. Use of different configuration files makes Struts applications easily configurable. Also, Struts is open source and hence, cost effective.

What steps are required to for an application migration from Struts1 to Struts2?

Following Steps are required for Struts1 to Struts2 migration:

Move Struts1 actionForm to Struts2 POJO.

Convert Struts1 configuration file (struts-config.xml) to Struts2 configuration file (struts.xml)

How properties of a form are validated in Struts?

For validation of populated properties, validate() method of ActionForm class is used before handling the control of formbean to Action class.

What's the use of reset method of ActionForm class?

reset method of actionForm class is used to clear the values of a form before initiation of a new request.

What are disadvantages of Struts?

Although Struts have large number of advantages associated, it also requires bigger learning curve and also reduces transparency in the development process.

Struts also lack proper documentation and for many of its components, users are unable to get proper online resources for help.

What's the use of resourcebundle.properties file in Struts Validation framework?

resourcebundle.properties file is used to define specific error messages in key value pairs for any possible errors that may occur in the code.

This approach helps to keep the code clean as developer doesn’t need to embed all error messages inside code.

Can I have html form property without associated getter and setter formbean methods?

For each html form property, getter and setter methods in the formbean must be defined otherwise application results in an error.

How many servlet controllers are used in a Struts Application?

Struts framework works on the concept of centralized control approach and the whole application is controlled by a single servlet controller. Hence, we require only one servlet controller in a servlet application.

For a single Struts application, can we have multiple struts-config.xml files?

We can have any number of Struts-config.xml files for a single application.

We need following configurations for this:

[xml]

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>

org.apache.struts.action.ActionServlet

</servlet-class>

<init-param>

<param-name>config</param-name>

<param-value>

/WEB-INF/struts-config.xml

/WEB-INF/struts-config_user.xml

/WEB-INF/struts-config_admin.xml

</param-value>

</init-param>

………….

………….

</servlet>

[/xml]

Which model components are supported by Struts?

Struts support all types of models including Java beans, EJB, CORBA. However, Struts doesn’t have any in-built support for any specific model and it’s the developer’s choice to opt for any model.

When it's useful to use IncludeAction?

IncludeAction is action class provided by Struts which is useful when an integration is required between Struts and Servlet based application.

Is Struts thread safe?

Yes Struts are thread safe. In Struts, a new servlet object is not required to handle each request; rather a new thread of action class object is used for each new request.

What configuration changes are required to use resource files in Struts?

Resource files (.properties files) can be used in Struts by adding following configuration entry in struts-config.xml file:

<message-resources parameter=”com.login.struts.ApplicationResources”/>

How nested beans can be used in Struts applications?

Struts provide a separate tag library (Nested Tag Library) for this purpose. Using this library, we can nest the beans in any Struts based application.

What are the Core classes of Struts Framework?

Following are the core classes provided by Struts Framework:

Action Class

ActionForm Class

ActionMapping Class

ActionForward Class

ActionServlet Class

Can we handle exceptions in Struts programmatically?

Yes we can handle exceptions in Struts programmatically by using try, catch blocks in the code.

[java]

try {

// Struts code

}

Catch (Exception e) {

// exception handling code

}

[/java]

Is Struts Framework part of J2EE?

Although Struts framework is based on J2EE technologies like JSP, Java Beans, Servlets etc but it’s not a part of J2EE standards.

How action mapping is configured in Struts?

Action mappings are configured in the configuration file struts-config.xml under the tag <action-mapping> as follows:

[xml]

<pre><action-mappings>

<action path=”/login”

type=”login.loginAction”

name=”loginForm”

input=”/login.jsp”

scope=”request”

validate=”true”>

<forward name=”success” path=”/index.jsp”/>

<forward name=”failure” path=”/login_error.jsp”/>

</action>

</action-mappings>

[/xml]

When should be opt for Struts Framework?

Struts should be used when any or some of the following conditions are true:

A highly robust enterprise level application development is required.

A reusable, highly configurable application is required.

A loosely coupled, MVC based application is required with clear segregation of different layers.

Why ActionServlet is singleton in Struts?

In Struts framework, actionServlet acts as a controller and all the requests made by users are controlled by this controller. ActionServlet is based on singleton design patter as only one object needs to be created for this controller class. Multiple threads are created later for each user request.

What are the steps required for setting up validator framework in Struts?

Following Steps are required to setup validator framework in Struts: –

In WEB-INF directory place valdator-rules.xml and validation.xml files.

Enable validation plugin in struts-config.xml files by adding following:

[xml]

<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>

<set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml,

/WEB-INF/validation.xml”/>

</plug-in>

[/xml]

Which technologies can be used at View Layer in Struts?

In Struts, we can use any of the following technologies in view layer:

JSP

HTML

XML/XSLT

WML Files

Velocity Templates

Servlets

What are the conditions for actionForm to work correctly?

ActionForm must fulfill following conditions to work correctly:

It must have a no argument constructor.

It should have public getter and setter methods for all its properties.

Which library is provided by Struts for form elements like check boxes, text boxes etc?

Struts provide HTML Tags library which can be used for adding form elements like text fields, text boxes, radio buttons etc.

Related Posts Plugin for WordPress, Blogger...
Flag Counter