Home
=============================================================================
What is the disadvantage of DispatchAction
=============================================================================
The main constraint in the DispatchAction is the method name in the action class and the button name in the jsp page should be the same. But in LookupDispatchAction, we can have different names for the buttons and the methods.
Home
=============================================================================
What is LookupDispatchAction in struts
=============================================================================
Steps
1) Your action class has to extends to LookupDispatchAction
2) You have to implement protected Map getKeyMethodMap()
public class UserAction extends LookupDispatchAction
{
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("UserEmployeeForm.add", "addEmployeeDetails");
map.put("UserEmployeeForm.update", "manageEmployeePersonalDetail");
map.put("UserEmployeeForm.delete", "processVoluntaryRetirement");
return map;
}
public ActionForward addEmployeeDetails(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("Inside addEmployeeDetails method.");
return mapping.findForward(SUCCESS);
}
public ActionForward manageEmployeePersonalDetail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("Inside manageEmployeePersonalDetail method.");
return mapping.findForward(SUCCESS);
}
public ActionForward processVoluntaryRetirement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("Inside processVoluntaryRetirement method.");
return mapping.findForward(SUCCESS);
}
}
3) Add action mapping in struts config.xml with parameter="method"
4) Add entry In ApplicationResource.properties file. each key is mapped to a value, that value represents the button name in the jsp page. You have to give Add, Update and Delete as button name in your jsp page.
ApplicationResource.properties
------------------------------
UserEmployeeForm.add = Add
UserEmployeeForm.update = Update
UserEmployeeForm.delete = Delete
Disadvantages:
You still have to deal with ApplicationResource.properties and implementation of getKeyMethodMap()
Advantage:
The main constraint in the DispatchAction is the method name in the action class and the button name in the jsp page should be the same. But here in LookupDispatchAction, we can have different names for the buttons and the methods. If you change button names in future , there will not be any java code change. Simply change your resources.xml file deploy.
Home
======================================================================
What is DynaActionForm Bean
======================================================================
DynaActionForm Beans are the extension of Form Beans that allows you to specify the form properties inside the struts configuration file instead of creating a seperate concreate class.
Steps
1) Declare the DynaactionForm bean in struts-config.xml file
2) Access the form bean like below shown. We have done (DynaActionForm) form; type casting. And then you can get the attributes of the form like normla formBean.
public class LoginAction extends org.apache.struts.action.Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception {
DynaActionForm loginForm = (DynaActionForm) form;
String userName = loginForm.get("userName").toString();
String password = loginForm.get("password").toString();
}
Advantages:
It will become tedious to create a seperate form bean for each action class. Using DynaActionForm we can easily create Form Bean in struts-config.xml file.
Home
======================================================================
What is validator framework
======================================================================
The Validator Framework in Struts consist of two XML configuration files.
1) validator-rules.xml 2) validation.xml
Step
The Validator Framework in Struts consist of two XML configuration files.
1) validator-rules.xml 2) validation.xml
Step
1) add framework in the Struts configuration files as shown below.
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
2)Next step is to add validations to the form fields in the validation.xml file.
<form-validation>
<formset>
<form name="LoginForm">
<field property="userName" depends="required">
<arg key="LoginForm.userName"/>
</field>
</form>
</formset>
</form-validation>
3)The error message to be displayed is specified in the ApplicationResource.properties file.
LoginForm.userName = User Name
errors.required={0} is required.
At run time if you dont give user name field and click on submit button, you will get "User Name is required" as an error message. Prefix of error message we have defined in validator.xml as arg key tag and post will be automatically taken by validator framework.
Home
=====================================================================
Client-Side JavaScript Validation in struts using Validator framework
How do you do clinet side validation in struts ?
Is it possible to use validator framework at client side?
=============================================================================
Advantages:
It's very useful to validate some fields on the client-side before sending the data to the server for processing. By this way we can ensure that the data send to the server is valid. Performing validations on the client-side save the user a round trip time to the server. For each validation routine defined in the validation-rules.xml file Struts provides an optional JavaScript code that can run on the client-side to perform the same validation
Steps:
1) LoginForm extends DynaValidatorForm.
<form-bean name="LoginForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="userName" type="java.lang.String" />
<form-property name="password" type="java.lang.String" />
</form-bean>
2) Add validation in validation.xml file.
3)To enable client-side validation you have to place the Struts HTML Tag Library's javascript tag in each jsp page for which you need to preform client-side validation.
<html:form action="/Login" onsubmit="validateLoginForm(this);">
<html:javascript formName="LoginForm" />
User Name : <html:text name="LoginForm" property="userName" /> <br>
Password : <html:password name="LoginForm" property="password" /> <br>
<html:submit value="Login" />
</html:form>
Struts will generate javaScript code for you.The name of the validate method generated by the javascipt tag is formed by concatenating "validate" with the name of the form specified in the javascript. For example, our form name is "LoginForm" so the generated method name will be "validateLoginForm".
Home
======================================
How do you handle exceptions in struts
======================================
case 1 ==>Declarative exception handling
Consider the method signature for the execute method in the Struts Action class.
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
The execute() method has java.lang.Exception in its throws clause. Hence you don\x{2019}t have to handle the exceptions explicitly in Action.
<struts-config>
<action>
<exception
key="database.error.duplicate"
path="/UserExists.jsp"
type="mybank.account.DuplicateUserException"/>
<exception
key="rmi.error"
type="java.rmi.RemoteException"
path="/rmierror.jsp"/>
</action>
the declarative exception handling was local to the CustomerAction. You can add global declarative exception handling too. For instance, if you want to handle the RemoteException in the same way across the board, use the following approach:
<struts-config>
<global-exceptions>
<exception
key="rmi.error"
type="java.rmi.RemoteException"
path="/rmierror.jsp"/>
</global-exceptions>
</struts-config>
Case 2
Using the ExceptionHandler
ActionError class object is generated by system.
catch (DuplicateUserException due)
{
ActionErrors errors = new ActionErrors();
ActionError error = new ActionError(\x{201C}userid.taken\x{201D},due.getUserId());
}
Home
======================================
What is interceptor in struts
======================================
Interceptors is a Class which is called before and after Action called.Many Actions need some common funcitonality to executed before action execution. Like Some Actions need
1) input validated.
2)Other Actions may need a file upload to be pre-processed.
3)protection from a double submit.
4) Many Actions need drop-down lists and other controls pre-populated before the page displays.
Interceptors can execute code before and after an Action is invoked. Most of the framework's core functionality is implemented as Interceptors. Each and every Interceptor is pluggable, so you can decide exactly which features an Action needs to support.
Configuring Interceptors
struts.xml
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="timer" class=".."/>
<interceptor name="logger" class=".."/>
</interceptors>
<action name="login"
class="tutorial.Login">
<interceptor-ref name="timer"/>
<interceptor-ref name="logger"/>
<result name="input">login.jsp</result>
<result name="success"
type="redirectAction">/secure/home</result>
</action>
</package>
Stacking Interceptors
As above example we have given interceptor-ref in the action tag, we may need to configure interceptors many times with many acitons.
Despite of reeterating the same iterceptor list again and again we can stak them in one place, and that can be access globally.
<interceptor-stack name="basicStack">
<interceptor-ref name="exception"/>
<interceptor-ref name="servletConfig"/>
<interceptor-ref name="multiselect"/>
<param name="excludeParams">dojo\..*,^struts\..*</param>
</interceptor-ref>
<interceptor-ref name="conversionError"/>
</interceptor-stack>
<!-- Sample validation and workflow stack -->
<interceptor-stack name="validationWorkflowStack">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="validation"/>
</interceptor-stack>
<!-- Sample JSON validation stack -->
<interceptor-stack name="jsonValidationWorkflowStack">
<interceptor-ref name="basicStack"/>
<interceptor-ref name="validation">
<param name="excludeMethods">input,back,cancel</param>
</interceptor-ref>
<interceptor-ref name="jsonValidation"/>
<interceptor-ref name="workflow"/>
</interceptor-stack
Home
======================================
What is the difference actionServlet and requestProcessor
======================================
There is "controller" in struts which is core of struts and does work of contolling entire flow.
The controller is implemented by a java servlet. In struts framework the controller responsibilities are implemented by several different components like
1. ActionServlet
2. requestProcessor
3. requstDispatcher
1) The ActionServlet Class
The ActionServlet extends the javax.servlet.http.httpServlet class.
2) The RequestProcessor Class
The class org.apache.struts.action.requestProcessor process the request from the controller.
1) Action servlet calls doGet() and doPost() methods when requst is received form the client
2) RequestProcessor calls process method for processing request
Home
======================================
Is Struts 1.2 action classes thread safe
======================================
I read this form http://struts.apache.org/1.x/userGuide/building_controller.html
keyPoints
1) Struts 1.2 action classes are SingleTon and hence only one object of aciton
class will be created for all the request
2) If there are multiple threads or multiple request comming to same aciotn class
at the same time, it will share same object and hence its not thread safe
How to avoid this for making it thread safe
3) Only Use Local Variables - The most important principle that aids in
thread-safe coding is to use only local variables, not instance variables ,
in your Action class. Local variables are created on a stack that is assigned
(by your JVM) to each request thread
4) conserve Resources - using session so only one user can use it.
Home
======================================
Is Aciton Form (formBean) is thread safe
======================================
In struts-config.xml we define <action> tag. The 'scope' attribute may be either
'request' or 'session'. If the scope is request, then the Strut's request processor
will create a new bean for each request. In this case, access to the bean attributes
is thread-safe, unless you created your own thread and pasted the bean to that thread
If the scope is declared to be session, then the formBean is created when it
is first needed (by some action) and then potentially accessed by subsequent
requests.