struts

"Struts "


Struts

1 )   What is Struts ?

Ans)

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

Ans)

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

Ans)
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 ?

Ans)

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

Ans)
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" ?

Ans)
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 ?

Ans)
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 ?

Ans)
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.
IncludeAction:
<action path="/saveDetail" type="org.apache.struts.actions.IncludeAction"
name="detailForm" scope="request" input="/detail.jsp" parameter="/path to processing servlet">
ForwardAction:
<action path="/saveSubscription" type="org.apache.struts.actions.ForwardAction"
name="subscriptionForm" scope="request" input="/subscription.jsp"
parameter="/path/to/processing/servlet"/>

  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 ?

Ans)
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"
        type="org.apache.struts.action.DynaActionForm">
    <form-property name="username" type="java.lang.String"/>
</form-bean>



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

Ans)
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 ?

Ans)
Struts Validation Framework Example, please follow the Steps.
Step 1:
A simple validator-rules.xml File
<form-validation>
 <global>
  <validator
     name="required"
     classname="org.apache.struts.util.StrutsValidator"
     method="validateRequired"
     methodparams="java.lang.Object,
                   org.apache.commons.validator.ValidatorAction,
                   org.apache.commons.validator.Field,
                   org.apache.struts.action.ActionErrors,
                   javax.servlet.http.HttpServletRequest"
     msg="errors.required"/>
  
  <validator name="minlength"
     classname="org.apache.struts.util.StrutsValidator"
     method="validateMinLength"
     methodparams="java.lang.Object,
                   org.apache.commons.validator.ValidatorAction,
                   org.apache.commons.validator.Field,
                   org.apache.struts.action.ActionErrors,
                   javax.servlet.http.HttpServletRequest"
     depends="required"
     msg="errors.minlength"/>
 </global>
</form-validation>

Step 2: validation.xml
<form-validation>
 <formset>
  <form name="checkoutForm">
    <field
      property="firstName"
      depends="required">
      <arg0 key="label.firstName"/>
    </field>
      
    <field 
      property="lastName"
      depends="required">
      <arg0 key="label.lastName"/>
    </field>
  </form>
 </formset>
</form-validation>

Step 3: Add this ti Struts-Config.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>
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 java.io.Serializable;
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 ?

Ans)
<plug-in className=”org.apache.struts.validator.ValidatorPlugIn”>
    <set-property property=”pathnames”
     value=”/WEB-INF/validator-rules.xml,
            /WEB-INF/validation.xml”/>
  </plug-in>
validation.xml:
<form-validation>
  <formset>
    <form name=”logonForm”>
      <field property=”username”
              depends=”minlength,...”>
        <arg0 key=”prompt.username”/>
        <arg1 key=”${var:minlength}”
             name=”minlength”
         resource=”false”/>
        <var><var-name>minlength</var-name>
          <var-value>3</var-value></var>
      </field>
    </form>
  </formset>
</form-validation>



13 )   How to use Structs tag libs in Jsp ?

Ans)
<%@ 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”>
<head>
  <title>
    <bean:message key=”logon.title”/>
  </title>
  <html:base/>
</head>
<body bgcolor=”white”>
<html:errors/>
<html:form action=”/logon” focus=”username”
        onsubmit=”return validateLogonForm(this);”>
<table border=”0” width=”100%”>
  <tr>
    <th align=”right”>
    <bean:message key=”prompt.username”/>
    </th>
    <td align=”left”>
      <html:text property=”username” size=”16”/>
    </td>
  </tr>
</html:form>
</body></html:html>



14 )   Some Sample Struts HTML tags ?

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




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

Ans)
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" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
  <data-sources>
  </data-sources>

  <form-beans>
    <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"/>
  </form-beans>

  <global-exceptions>
  </global-exceptions>

  <global-forwards>
  </global-forwards>

  <action-mappings>

    <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"/>
    </action>
 
  </action-mappings>

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



16 )    What is "global-forwards" ?

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



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

Ans)
<servlet>
    <servlet-name>Controller</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
      </param-value>
    </init-param>
    <load-on-startup> 1 </load-on-startup>
  </servlet>



18 )   How to use Action Errors ?

Ans)
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) {
     errors.add(GLOBAL_ERROR,
     new ActionError("error.custform"));
   }
ii) Dispay these in JSP as follows.
   <html:errors/>



19 )   How you read MessageResources in Struts ?

Ans)
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>
</html:messages>
In property file data.do configured as below
data.do=Please {0}




20 )   Struts 1.x VS Struts 2.0 ?

Ans)
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 ?

Ans)



22 )   Quick Struts 2.0 Example ?

Ans)
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <title>Hello World!</title>
    </head>
    <body>
        <h2><s:property value="message" /></h2>
    </body>
</html>
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 {
        setMessage(MESSAGE);
        return SUCCESS;
    }
    public void setMessage(String message){
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="tutorial" extends="struts-default">
        <action name="HelloWorld" class="tutorial.HelloWorld">
            <result>/HelloWorld.jsp</result>
        </action>
        <!-- Add your actions here -->
    </package>
</struts>



23 )   How you access Session, HttpServletRequest ,HttpServletResponse ?

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





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

Ans)
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
 struts.properties file, and place the file under WEB-INF/classes, next to the struts.xml.
struts.ui.theme=simple