"Struts "


1 )   What is Struts ?


  • null
    Sample Img 1
Apache Struts is an open-source framework for developing Java EE web applications. 
It uses and extends the Java Servlet API to encourage developers to adopt a model-view-controller (MVC) architecture.

2 )   What is the MVC in struts ?


  • Struts MVC
    Sample Img 2
Divides the overall functionality of an application into three layers:
Model Layer – Contains the functional business logic of the application, as well as a representation
of the persistently stored data backing the application
View Layer – Contains the user interface, including mechanisms to accept user input and render results
Controller Layer – Contains the logic that manages the flow of individual requests, dispatching to the
appropriate business logic component

3 )   What is ActionServlet ?

ActionServlet provides the "controller" in the Model-View-Controller (MVC) design pattern for web
applications that is commonly known as "Model 2".
The controller manages the handling of the request, including invoking security services such as
authentication and authorization
, delegating business processing, managing the choice of an
appropriate view, handling errors, and managing the selection of content creation strategies.

4 )   What is Model 2 Architecture ?


  • Model 2 Architecture
    Sample Img 4
As per the "Model 2 Architecture", the Incoming requests flow through a common path as shown below:
i) Received by common component    (ActionServlet A Front Controller)
ii) Standardized request pre-processing (RequestProccessor )
iii) Dispatch to request-specific model component (Action class)
vi) Forward to business-logic-specified view component (Jsp)
V) Standardized request post-processing

5 )   What is Front Controller in Struct ?

The controller manages the handling of the request, including invoking security services
such as authentication and authorization
, delegating business processing, managing the choice
of an appropriate view, handling errors, and managing the selection of content creation strategies.
In Struts "ActionServlet" plays that role.

6 )   What is "RequestProcessor" ?

The RequestProcessor selects and invokes an Action class to perform the requested business
logic, or delegates the response to another resource.
Standard Request Processing Lifecycle 1:
processLocale() -- Record user's locale preference (if not already present)
processPreprocess() -- general purpose pre-processing hook
processMapping() -- select Action to be utilized
processRoles() -- perform security role-based restrictions on action execution
processActionForm() -- Create or acquire an appropriate ActionForm instance

7 )   What is the Action Class ?

An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class.
Action class acts as wrapper around the business logic and provides an inteface to the application's
Model layer.
 It acts as glue between the View and Model layer. It also transfers the data from the
view layer to the specific business process layer and finally returns the procssed data from business
layer to the view layer.
Few Facts about Action Class
i) Single instance per application (not thread safe)
ii) Instantiated as needed, like servlets
Sample Action Class :
public class TestYourAction extends Action
  public ActionForward execute(
  ActionMapping mapping,
  ActionForm form,
  HttpServletRequest request,
  HttpServletResponse response) throws Exception{
  return mapping.findForward("testAction");

8 )   Please tell some of different kind of Action classes available ?

The different kinds of actions are done by the following:
Forward Action,Include Action, DispatchAction.
Dispatch Action
The dispatch action is meant to be a workload reducer. It allows you to use
"org.apache.struts.actions.DispatchAction" to combine functions that are related into a single
action instead of having to create a new action for each required function. For example, within
a dispatch action you could include multiple forward actions.
<action path="/saveDetail" type="org.apache.struts.actions.IncludeAction"
name="detailForm" scope="request" input="/detail.jsp" parameter="/path to processing servlet">
<action path="/saveSubscription" type="org.apache.struts.actions.ForwardAction"
name="subscriptionForm" scope="request" input="/subscription.jsp"

  public class UserAction extends DispatchAction  {
        public ActionForward add(ActionMapping mapping, ActionForm form,
         HttpServletRequest request, HttpServletResponse response) {
        public ActionForward update(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        UserForm userForm = (UserForm) form;
        userForm.setMessage("Inside update user method.");
        return mapping.findForward(SUCCESS);

9 )   ActionForm VS DynaActionform ?

In case of 'DynaActionform ' you need to create any Java class, you could directly
 declare this in Struct-Config.xml file.
<form-bean name="dynaUserForm"
    <form-property name="username" type="java.lang.String"/>

10 )   How you could avoid multiple Form submissions (Posts or Clicks) in Struts ?

Mutli-click prevention by 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.
Step 2. Store Token key as a hidden field: ( empform.jsp)
Step 3. Check Token is Valid ?

11 )   Struct Validation Framework ?

Struts Validation Framework Example, please follow the Steps.
Step 1:
A simple validator-rules.xml File
  <validator name="minlength"

Step 2: validation.xml
  <form name="checkoutForm">
      <arg0 key="label.firstName"/>
      <arg0 key="label.lastName"/>

Step 3: Add this ti Struts-Config.xml
<plug-in classname="org.apache.struts.validator.ValidatorPlugIn">
Step 4: If you want to use the Custom Validator , if you want to use this
,please use this validator name in "validator-rules.xml"
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.GenericValidator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.commons.validator.ValidatorUtil;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.StrutsValidatorUtil;
public class YourOwnValidator implements Serializable{
  public static boolean validateAge( Object bean,
    ValidatorAction va,
    Field field,
    ActionErrors errors, HttpServletRequest request) {
    String value = null;
    if (isString(bean)) {
      value = (String) bean;
    } else {
      value =
        ValidatorUtil.getValueAsString(bean, field.getProperty());

  return true;
private static boolean isString(Object o) {
  if (o == null) {
    return (true);
  return (String.class.isInstance(o));

12 )   Struct Validation thru JavaScript ?

<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
    <set-property property=”pathnames”
    <form name=”logonForm”>
      <field property=”username”
        <arg0 key=”prompt.username”/>
        <arg1 key=”${var:minlength}”

13 )   How to use Structs tag libs in Jsp ?

<%@ page contentType=”text/html;charset=”UTF-8” %>
<%@ taglib uri=”/WEB-INF/struts-bean.tld”
    prefix=”bean” %>
<%@ taglib uri=”/WEB-INF/struts-html.tld”
    prefix=”html” %>
<html:html locale=”true”>
    <bean:message key=”logon.title”/>
<body bgcolor=”white”>
<html:form action=”/logon” focus=”username”
        onsubmit=”return validateLogonForm(this);”>
<table border=”0” width=”100%”>
    <th align=”right”>
    <bean:message key=”prompt.username”/>
    <td align=”left”>
      <html:text property=”username” size=”16”/>

14 )   Some Sample Struts HTML tags ?

<html:html locale=”true”>
<bean:message key=”prompt.username”/>
<html:text property=”username” size=”16”/>

15 )   What is "struts-config.xml" ?

Below is the sample Struts-Config XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "">

    <form-bean name="formBeanUser" type="com.yourApp.formbean.FormBeanUser"/>
    <form-bean name="formBeanCategory" type="com.yourApp.formbean.FormBeanCategory"/>
    <form-bean name="formBeanProduct" type="com.yourApp.formbean.FormBeanProduct"/>
    <form-bean name="formBeanCheckout" type="com.yourApp.formbean.FormBeanCheckout"/>




    <action path="/actionUserRegister" name="formBeanUser"
     type="com.yourApp.action.ActionUser" scope="request" input="/view/struts/register.jsp">
      <forward name="successRegister" path="/view/struts/framesetHome.jsp"/>
      <forward name="failureRegister" path="/view/struts/register.jsp"/>
      <forward name="error" path="/view/struts/error.jsp"/>

  <controller processorClass="org.apache.struts.tiles.TilesRequestProcessor"/>
  <message-resources parameter="com.yourApp.resources.MessageResources"/>

16 )    What is "global-forwards" ?

The forwards which are added in "<global-forwards>" could be accessed in any
    <forward name=”logoff” path=”/”/>
    <forward name=”logon”   path=”/”/>
    <forward name=”registration”
    <forward name=”success”

17 )   Changes to "Web.xml" ? Or How you config ActionServlet in Structs ?

    <load-on-startup> 1 </load-on-startup>

18 )   How to use Action Errors ?

In Action class, you could validate and add the Errors as shown below and you need
to display these in JSP page.
i) Add the Errors like this in Action Class:
   ActionErrors errors = new ActionErrors();
   if (parent == null) {
     new ActionError("error.custform"));
ii) Dispay these in JSP as follows.

19 )   How you read MessageResources in Struts ?

A class that encapsulates messages. Messages can be either global or they are specific
to a particular bean property. Each individual message is described by an ActionMessage object,
which contains a message key (to be looked up in an appropriate message resources database),
and up to four placeholder arguments used for parametric substitution in the resulting message.
data.saved=Data saved successfully
ActionMessages messages = new ActionMessages();
ActionMessage msg = new ActionMessage(“data.saved”);
messages.add(“message1?, msg);
<html:messages id=”msgId” message=”true” property=”message1?>
       <bean:write name=”msgId”/><br>
In property file configured as below {0}

20 )   Struts 1.x VS Struts 2.0 ?

Feature        Struts 1       Struts 2       
Action classes Struts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces.An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model  Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized.        Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)       
Servlet DependencyStruts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked.  
Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly. 

21 )   Important components in Struts 2.0 ?


22 )   Quick Struts 2.0 Example ?

<%@ taglib prefix="s" uri="/struts-tags" %>
        <title>Hello World!</title>
        <h2><s:property value="message" /></h2>
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
    private String message;
    public static final String MESSAGE = "Struts is up and running ...";
    public String execute() throws Exception {
        return SUCCESS;
    public void setMessage(String message){
        this.message = message;
    public String getMessage() {
        return message;
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    <package name="tutorial" extends="struts-default">
        <action name="HelloWorld" class="tutorial.HelloWorld">
        <!-- Add your actions here -->

23 )   How you access Session, HttpServletRequest ,HttpServletResponse ?

HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
Map attibutes = ActionContext.getContext().getSession();

24 )   Why do the form tags put table tags around controls ?

In Structs 2.0,
The form tags are designed to generate standard markup around control tags. What markup the
tags generate is determined by a "theme". A theme is a set of templates and stylesheets that
work together to generate the Struts Tags.
The simple theme does not inject any default markup, and lets us add whatever special markup we
 want around the tags. To use the simple theme throughout an application, we can add this line to the file, and place the file under WEB-INF/classes, next to the struts.xml.