Monday, October 13, 2008

STRUTS FAQ

Q.What is Action Class? Explain with Example ?

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.
An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it.
Then the struts controller (ActionServlet) slects an appropriate Action and Request Processor creates an instance if necessary,
and finally calls execute method of Action class.
To use the Action, we need to Subclass and overwrite the execute() method. and your bussiness login in execute() method.
The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the JSP as per the value of the returned ActionForward object.
ActionForward JSP from struts_config.xml file.

Developing our Action Class :

Our Action class (EmpAction.java) is simple class that only forwards the success.jsp.
Our Action class returns the ActionForward called "success", which is defined in the struts-config.xml file (action mapping is show later in this page).
Here is code of our Action Class
public class EmpAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("success");
}
}

mapping.findForward("success"); forward to JSP mentioned in struts_config.xml.
struts_config.xml configuration is :

path="/EmpAction"
type="com.techfaq.EmpAction">


mapping.findForward("success") method forward to success.jsp (mentioned in struts_config.xml);


Here is the signature of the execute() method Action Class.

public ActionForward execute(ActionMapping mapping,
ActionForm form,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
throws java.lang.Exception

Where
mapping - The ActionMapping used to select this instance
form - The optional ActionForm bean for this request (if any)
request - The HTTP request we are processing
response - The HTTP response we are creating
Throws:
Action class throws java.lang.Exception - if the application business logic throws an exception

In the browser : http://localhost:8080/testApp/EmpAction.do
This will call to execute() method of EmpAction and after that based on mapping.findForward("success") forward to success.jsp.

Setup your first Action class http://www.techfaq360.com/tutorial/struts_setup.jsp

Q.How you can do Exception Handling in Struts ?
There are two approaches available for the exception handling in struts.


Declarative:
Exceptions are defined in the struts-config.xml file and
if the exception occurs the control is automatically passed to the appropriate error page.
The tag is used to define the exception in the struts-config.xml file.

For Example : (( If RuntimeException in SaveEmpAaction class , control goes to exception.jsp)

type="com.techfaq.SaveEmpAaction"
input="/empform.jsp" >



Where

Key: The key defines the key present in MessageResources.properties file to describe the exception occurred.

Type: The class of the exception occurred.

Path: The page where the control is to be followed in case exception occurred.

Handler: The exception handler which will be called before passing the control to the file specified in path attribute

OR


Defining the Exceptions Globally for the struts-config.xml : ( If RuntimeException in any Action class , control goes to exception.jsp)





Programmatic:
In this approach the exceptions are caught using normal java language try/catch block and instead of showing the exception some meaningful messages are displayed.
In this approach the flow of control is also maintained by the programs.
The main drawback of the approach is the developer has to write the code for the flow of the application.


Q. What are the Advantages of Struts ?
Struts follow MVC framework. So the JSP, Java and Action classes are organized and easily maintainable.
Struts offers many advantages to the application programmer while reducing the development time and making the manageability of the application easier.
Advantages of Struts :


Centralized Configuration :
Rather than hard coding information into java programs,many Struts values are represented in XML or property files.
Struts_config.xml file is the place from where you can get all information?s about your web application. This is organized.
Your Action class , Form bean and JSP page information is in Struts_config.xml so don't need to search . All info in one place.



Form Beans :
Don't need to set the form vales to your value object . When you want to capture data from a form ( In the servlet you do request.getParameter()).
In the struts you don't need to do explicitly request.getParameter(). Struts request processor will do for you. All the input data will be set to form bean.



Bean Tags :
Struts provides a set of custom JSP tags (bean:write,in particular) that let you easily output the properties of JavaBeans components.
Basically,these are concise and powerful variations of the standard jsp:useBean and jsp:getProperty tags.


HTML tags :
Struts provides a set of custom JSP tags to create HTML forms that are associated with JavaBeans components.


Form Field Validation :

Apache Struts has built-in capabilities for checking that form values are in the required format.
If values are missing or in an improper format,the form can be automatically redisplayed with error messages and with the previously entered values maintained.
This validation can be performed on the server (in Java),or both on the server and on the client (in JavaScript).

How Iterate Tag used with a Map ?


User Id:
Password:



Q.How does client side validation using validator framework work in struts ?

There are two configuration files used.
One if called validator-rules.xml and the other is validation.xml.
This is example of client side validation :Java Script message.

Step 1.
In the JSP page : empform.jsp





Save







You have to add
in JSP for activate client side validation .

Step 2.
Add action mapping in struts-config.xml

path="/EmpSaveAaction"
type="empForm"
name="AddressForm"
scope="request"
validate="true"
input="/empform.jsp">



and add the form bean inside tag





Step 3.
validator-rules.xml :

The validator-rules.xml file defines the Validator definitions available for a given application.
The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
Example validator-rules.xml File :


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




Step 4.
validation.xml File :
The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.
validation.xml File




property="firstName"
depends="required">



property="lastName"
depends="required">






In the empForm firstName and lastName are the required filed.
So in the above configuration you can see we add for both firstName and lastName.
You can see depends="required" - "required" property is defind in validator-rules.xml.

In the resource bundle : application_resource.propertis file
label.firstName=First Name
label.lastName=Last Name

#Error messages used by the Validator
errors.required={0} is required.

Based on the validation.xml File configuration .
Error in jsp will be : Java Script message.
First Name is required.
Last Name is required.

{0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind .


Q. How to do File Upload in Struts ?

Step 1.
Create a form bean

public class FileUploadForm extends ActionForm
{
private FormFile file;

public FormFile getFile() {
return file;
}

public void setFile(FormFile file) {
this.file = file;
}
}


Step 2.

In the struts-config.xml file add
name="FileUploadForm"
type="com.techfaq.form.FileUploadForm"/>

Step 3.

add action mapping entry in the struts-config.xml file:

path="/FileUploadAndSave"
type="com.techfaq.action.FileUploadAndSaveAction"
name="FileUploadForm"
scope="request"
validate="true"
input="/pages/fileupload.jsp">



Step 4.
In the JSP

File Name



Upload File



Step 5.
In the Action class write the code

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
FileUploadForm myForm = (FileUploadForm)form;

// Process the FormFile
FormFile file = myForm.getFile();
String contentType = file.getContentType();
//Get the file name
String fileName = file.getFileName();
int fileSize = file.getFileSize();
byte[] fileData = file.getFileData();
//Get the servers upload directory real path name
String filePath = getServlet().getServletContext().getRealPath("/") +"uploadfile";
/* Save file on the server */
if(!fileName.equals("")){
System.out.println("Server path:" +filePath);
//Create file
File fileToCreate = new File(file, fileName);
//If file does not exists create file
if(!fileToCreate.exists()){
FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
fileOutStream.write(file.getFileData());
fileOutStream.flush();
fileOutStream.close();
}


}

return mapping.findForward("success");
}


File will be oploaded to "uploadfile" directory og your server.

Q. What is DynaActionForm ? and How you can retrive the value which is set in the JSP Page in case of DynaActionForm ?
DynaActionForm is 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.
DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, i
t makes the FormBean declarative and this helps the programmer to reduce the development time.

For Example : you have a EmpForm and you don't want a java class (EmpForm).
EmpForm has propertis
firstName, lastName, country

In the struts-config.xml file , declare the form bean
type="org.apache.struts.action.DynaActionForm">





Add action mapping in the struts-config.xml file:

name="EmpForm"
scope="request"
validate="true"
input="/pages/empform.jsp">






In the Action class.
public class EmpSaveAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{

DynaActionForm empForm = (DynaActionForm)form;
// this is the way you can retrive the value which is set in the JSP Page
String firstName = (String)empForm.get("firstName");
String lastName = (String)empForm.get("lastName");
return mapping.findForward("success");
}
}
}

In the JSP page



Q. How to Setup validator framework in Struts ?

Step 1.
place validator-rules.xml and validation.xml in the WEB-INF directory.

Step 2.
Add the blow lines to struts-config.xml




Step 3.
In the jsp add the tag


Step 4.
Add
struts.jar
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-fileupload.jar
commons-lang.jar
commons-logging.jar
commons-validator.jar

into WEB-INF/lib directory

Explanation :

There are two configuration files used.
One if called validator-rules.xml and the other is validation.xml.
This is example of server side validation :


validator-rules.xml :

The validator-rules.xml file defines the Validator definitions available for a given application.
The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
Example validator-rules.xml File :


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




validation.xml File :
The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.
validation.xml File




property="firstName"
depends="required">



property="lastName"
depends="required">






In the empForm firstName and lastName are the required filed.
So in the above configuration you can see we add for both firstName and lastName.
You can see depends="required" - "required" property is defind in validator-rules.xml.

In the resource bundle : application_resource.propertis file
label.firstName=First Name
label.lastName=Last Name

#Error messages used by the Validator
errors.required={0} is required.

Based on the validation.xml File configuration .
Error in jsp will be :
First Name is required.
Last Name is required.

{0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind .


Q.How does validator framework work in Struts ?
There are two configuration files used.
One if called validator-rules.xml and the other is validation.xml.
This is example of server side validation :


validator-rules.xml :

The validator-rules.xml file defines the Validator definitions available for a given application.
The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
Example validator-rules.xml File :


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




validation.xml File :
The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.
validation.xml File




property="firstName"
depends="required">



property="lastName"
depends="required">






In the empForm firstName and lastName are the required filed.
So in the above configuration you can see we add for both firstName and lastName.
You can see depends="required" - "required" property is defind in validator-rules.xml.

In the resource bundle : application_resource.propertis file
label.firstName=First Name
label.lastName=Last Name

#Error messages used by the Validator
errors.required={0} is required.

Based on the validation.xml File configuration .
Error in jsp will be :
First Name is required.
Last Name is required.

{0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind .



What are Validators? and What are Basic Validators provided by the framework ?
Validator is a Java class that, when called by the Validator framework, executes a validation rule. The framework knows how to invoke a Validator class based on its method signature, as defined in a configuration file.

1) byte,short,integer,long,float,double

2) creditCard - Checks if the field is a valid credit card number.
3) date - Checks if the field is a valid date.
4) email - Checks if the field is a valid email address.
4) mask - Succeeds if the field matches the corresponding regular expression mask.
5) maxLength - Checks if the value's length is less than or equal to the given maximum length.
6) minLength - Checks if the value's length is greater than or equal to the given minimum length.
7) range - Checks if the value is within a minimum and maximum range.
8) required - Checks if the field isn't null and length of the field is greater than zero, not including whitespace.


What is the Benefits of Using the Validator framework in struts ?
A few of the benefits include:

1) A single definition of validation rules for an application.

2) Validation rules are loosely coupled to the application.

3) Server-side and client-side validation rules can be defined in one location.

4) Configuration of new rules and/or changes to existing rules are made simpler.

5) Supports Internationalization.

6) Supports regular expressions.

7) Can be used for both Web-based and standard Java applications.

8) Promotes a declarative approach rather than a programmatic one.

Q. What is the Difference between DispatchAction and LookupDispatchAction ?
LookupDispatchAction is subclass of DispatchAction.
In case of DispatchAction, you have to declare the method name in the JSP page.
For Example :
http://localhost:8080/emp/empaction.do?step=add // IN CASE OF DispatchAction
here step=add , we are delaring method name in JSP.
or
Add //IN CASE OF DispatchAction
so we can't use localization for button.


To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.

In the LookupDispatchAction :
For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. LookupDispatchAction is the answer to this
problem. With LookupDispatchAction, you can combine all three Actions into one.

Example :
Step 1.
three buttons might be










//No need method name declaration in JSP . Button name from resource bundle.

Step 2.
In the the Resource Bundle. //Here you can add localization.
button.add=Add
button.delete=Delete
button.update=Update

Step 3.
Implement a method named getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method returns a java.util.Map. The
keys used in the Map should be also used as keys in Message Resource
Bundle.

public class EmpAction extends LookupDispatchAction {

public Map getKeyMethodMap()
{
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
map.put("button.update", "update");
}


public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("add-success");
}

public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("delete-success");
}

public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("update-success");
}

}

in struts-config.xml

input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
path="addEmpSuccess.jsp"
redirect="true"/>
path="deleteEmpSuccess.jsp"
redirect="true"/>
path="updateEmpSuccess.jsp"
redirect="true"/>


for every form submission, LookupDispatchAction does the
reverse lookup on the resource bundle to get the key and then gets the method
whose name is associated with the key from
getKeyMethodmap().


Flow of LookupDispatchAction:
a) Form the button name "Add" get the key "button.add" fro resource bundle.
b) then in the Map getKeyMethodMap() find the value associated with the key "button.add".
c) value from the Map is "add" . then call add() method of the same action class.


Q. What is LookupDispatchAction?
When a set of actions is closely related and
separating them into multiple Actions would result in duplication of code you can use LookupDispatchAction.
LookupDispatchAction is subclass of DispatchAction.

In case of DispatchAction, you have to declare the method name in the JSP page.
For Example :
http://localhost:8080/emp/empaction.do?step=add // IN CASE OF DispatchAction
here step=add , we are delaring method name in JSP.
or
Add //IN CASE OF DispatchAction
so we can't use localization for button.


To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.

For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. LookupDispatchAction is the answer to this
problem. With LookupDispatchAction, you can combine all three Actions into one.

Example :
Step 1.
three buttons might be










//No need method name declaration in JSP . Button name from resource bundle.

Step 2.
In the the Resource Bundle. //Here you can add localization.
button.add=Add
button.delete=Delete
button.update=Update

Step 3.
Implement a method named getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method returns a java.util.Map. The
keys used in the Map should be also used as keys in Message Resource
Bundle.

public class EmpAction extends LookupDispatchAction {

public Map getKeyMethodMap()
{
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
map.put("button.update", "update");
}


public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("add-success");
}

public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("delete-success");
}

public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("update-success");
}

}

in struts-config.xml

input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
path="addEmpSuccess.jsp"
redirect="true"/>
path="deleteEmpSuccess.jsp"
redirect="true"/>
path="updateEmpSuccess.jsp"
redirect="true"/>


for every form submission, LookupDispatchAction does the
reverse lookup on the resource bundle to get the key and then gets the method
whose name is associated with the key from
getKeyMethodmap().

Flow of LookupDispatchAction:
a) Form the button name "Add" get the key "button.add" fro resource bundle.
b) then in the Map getKeyMethodMap() find the value associated with the key "button.add".
c) value from the Map is "add" . then call add() method of the same action class.


Q.How to create a multiple selections list in Struts? and retrive seleted values ?
This is the code to display multiple selections list and retrive seleted values in struts.
medList list contains list of Medium objects.

Java :
bean class.
public class Medium {
int medId;
String medName;

/**
* @return Returns the medId.
*/
public int getMedId() {
return medId;
}
/**
* @param medId The medId to set.
*/
public void setMedId(int medId) {
this.medId = medId;
}
/**
* @return Returns the medName.
*/
public String getMedName() {
return medName;
}
/**
* @param medName The medName to set.
*/
public void setMedName(String medName) {
this.medName = medName;
}
}

In the Form Class :

public class MediumForm {
private List medList;
private String[] med;
public void setMedList(List medList){
this.medList = medList;
}

public List getMedList(){
return this.medList;
}

public String[] getMed() {
return med;
}

public void setMed(String[] med) {
this.med = med;
}


}

In the Action class :

List medList = DAO.getMediums();
form.setMedList(medList);

DAO Class :

DAO Class to retrive mediums in data base.
public static List getMediums(){
PreparedStatement pStmt = null;
Connection conn = null;
boolean success = false;
ResultSet rs = null;
List medList = new ArrayList();

try{
conn = getConnection();

String sql = " select * from MEDIUM ";
pStmt = conn.prepareStatement(sql);

rs = pStmt.executeQuery();
while(rs.next()){
Medium med = new Medium();
med.setMedId(rs.getInt("MED_ID"));
med.setMedName(rs.getString("MEDIUM_NAME"));
medList.add(med);
}



}catch(Exception e){
e.printStackTrace();

}finally{
closeConnectionProp(conn,pStmt,rs);
}

return medList;

}

JSP Struts:









In the Action class again :
how to retrive the selected values.

String[] med = form.getMed();

Q.How to create a drop down list in Struts?
This is the code to display drop down list and retrive seleted value in struts.
medList list contains list of Medium objects.

Java :
bean class.
public class Medium {
int medId;
String medName;

/**
* @return Returns the medId.
*/
public int getMedId() {
return medId;
}
/**
* @param medId The medId to set.
*/
public void setMedId(int medId) {
this.medId = medId;
}
/**
* @return Returns the medName.
*/
public String getMedName() {
return medName;
}
/**
* @param medName The medName to set.
*/
public void setMedName(String medName) {
this.medName = medName;
}
}

In the Form Class :

public class MediumForm {
private List medList;
private String med;
public void setMedList(List medList){
this.medList = medList;
}

public List getMedList(){
return this.medList;
}

public void setMed(String medList){
this.med = med;
}

public String getMed(){
return this.med;
}


}

In the Action class :

List medList = DAO.getMediums();
form.setMedList(medList);

DAO Class :

DAO Class to retrive mediums in data base.
public static List getMediums(){
PreparedStatement pStmt = null;
Connection conn = null;
boolean success = false;
ResultSet rs = null;
List medList = new ArrayList();

try{
conn = getConnection();

String sql = " select * from MEDIUM ";
pStmt = conn.prepareStatement(sql);

rs = pStmt.executeQuery();
while(rs.next()){
Medium med = new Medium();
med.setMedId(rs.getInt("MED_ID"));
med.setMedName(rs.getString("MEDIUM_NAME"));
medList.add(med);
}



}catch(Exception e){
e.printStackTrace();

}finally{
closeConnectionProp(conn,pStmt,rs);
}

return medList;

}

JSP Struts:









In the Action class again :
how to retrive the select value.

String med = form.getMed();

Q. What is DispatchAction ?
When a set of actions is closely related and
separating them into multiple Actions would result in duplication of code you can use DispatchAction.
For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. DispatchAction is the answer to this
problem. With DispatchAction, you can combine all three Actions into one.

three urls might be
http://localhost:8080/emp/empaction.do?step=add
http://localhost:8080/emp/empaction.do?step=delete
http://localhost:8080/emp/empaction.do?step=update

public class EmpAction extends DispatchAction {
public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("add-success");
}

public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("delete-success");
}

public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("update-success");
}

}

in struts-config.xml

input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
path="addEmpSuccess.jsp"
redirect="true"/>
path="deleteEmpSuccess.jsp"
redirect="true"/>
path="updateEmpSuccess.jsp"
redirect="true"/>


Notice that one of the HTTP request parameter in the four URLs is also named "step". Now, it is all coming
together. DispatchAction knows what parameter to look for in the incoming
URL request through this attribute named parameter in struts-config.xml.


Q. What is IncludeAction ?

IncludeAction included resulting resource in the HTTP response .
In the JSP which don't use struts for include we do


In struts JSP


In the struts-config.xml
parameter="/test/LegacyServletA"
type="org.apache.struts.actions.IncludeAction" />

Q. How to Protect JSPs from direct access ?
JSPs located in the WEB-INF and its sub-directories are protected from outside access.
If you want to go pageB.jsp from pageA.jsp
Go to Page B

in the struts-config.xml
parameter="/WEB-INF/pageB.jsp"
type="org.apache.struts.actions.ForwardAction"/>

Q. What is ForwardAction ?
Suppose you want to go from PageA.jsp to PageB.jsp in your Struts
application. The easy way of achieving this is to add a hyperlink in PageA.jsp as
follows:
Go to Page B
or even better, as follows:
Go to Page B
However this violates the MVC spirit by directly accessing
the JSP.
Struts provides a built-in Action class called ForwardAction to address this
issue. With ForwardAction, the Struts Controller is still in the loop while
navigating from PageA to PageB. There are two steps involved in using the
ForwardAction. They are:
_ First, declare the PageA hyperlink that takes you to PageB as follows:
Go to Page B
_ Next, add an ActionMapping in the Struts Config file as follows:
parameter="/PageB.jsp"
type="org.apache.struts.actions.ForwardAction" />

How does reset() and Validate() method struts work ?
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.
Example:
/**
* Reset the form.
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {

super.reset(mapping,request);
this.password = null;
this.username = null;
this.guest = null;
}

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

Example :
/**
* Validate the form's input.
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if(username == null){
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.username.required"));
}
return errors;
}

Multiple buttons in struts using java script?
Example :
JSP Page


Fax



Email




 


In the Java Script


Integration Struts Spring Hibernate ?
Code is here with explanation



Step 1.
In the struts-config.xml add plugin

value="/WEB-INF/applicationContext.xml"/>



Step 2.

In the applicationContext.xml file
Configure datasourse

oracle.jdbc.driver.OracleDriver

jdbc:oracle:thin:@10.10.01.24:1541:ebizd

sa




Step 3.

Configure SessionFactory





com/test/dbxml/User.hbm.xml




net.sf.hibernate.dialect.OracleDialect





Step 4.
Configure User.hbm.xml













Step 5.

In the applicationContext.xml ? configure for DAO





Step 6.

DAO Class
public class UserDAOHibernate extends HibernateDaoSupport implements UserDAO {
private static Log log = LogFactory.getLog(UserDAOHibernate.class);

public List getUsers() {
return getHibernateTemplate().find("from User");
}

public User getUser(Long id) {
return (User) getHibernateTemplate().get(User.class, id);
}

public void saveUser(User user) {
getHibernateTemplate().saveOrUpdate(user);

if (log.isDebugEnabled()) {
log.debug("userId set to: " + user.getId());
}
}

public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id);
getHibernateTemplate().delete(user);
}
}

Q.Mutli-click prevention using struts tokens with code example.
Struts has 3 methods use for the token, saveToken(), isTokenValid() and resetToken().
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

Example :
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;
forward=mapping.findForward("FirstPage");// this is the jsp page where you want to struts tokens.
saveToken(request);

return forward;
}
}

Step 2.
If the token successfully created, when view source on the browser you will see the token, the token key is stored as a hidden field:
In jsp page :

<%@ 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" %>

First Page




value="<%= session.getAttribute(Action.TRANSACTION_TOKEN_KEY) %>" >





Step 3. Your logic
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)
{
ActionForward forward=mapping.findForward("submitForm");
DupSubmitForm frm=(DupSubmitForm)form;

if(isTokenValid(request))
{

System.out.println("frm.getName()"+frm.getName());
resetToken(request);
}
else
{
System.out.println("frm.getName()"+frm.getName());
System.out.println("Duplicate Submission of the form");

}
return forward;
}
}



Q. How to prevent mutli-click using struts tokens ?

Struts has 3 methods use for the token, saveToken(), isTokenValid() and resetToken().
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.

How it works:
1. 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. If the token successfully created, when view source on the browser you will see something similar to the following, the token key is stored as a hidden field:

name="<%= Constants.TOKEN_KEY %>"
value="<%= session.getAttribute(Action.TRANSACTION_TOKEN_KEY) %>" >

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

.
In Action Class.

public final ActionForward perform(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
saveToken(request);
if (!tokenIsValid(request))
{
//forward to error page saying "your transaction is already being processed"
else
{
//process action
//forward to jsp
}

// Reset token after transaction success.
resetToken(request);

}


Q.How you will enable front-end validation based on the xml in validation.xml?
The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form ?logonForm? as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

Q.What is new in ServletRequest interface ?
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()

Q.Struts Action Chaining?
Chaining actions can be done by simply using the
proper mapping in your forward entries in the struts-config.xml file.

public class AAction extends Action
{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something

return mapping.findForward("success");
}
}



/* com/BAction.java */
...

public class BAction extends Action
{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something else

return mapping.findForward("success");
}
}


Then you can chain together these two actions with
the Struts configuration as shown in the following excerpt:


...

type="com.AAction"
validate="false">


type="com.BAction"
scope="session"
validate="false">





Q.How can I avoid validating a form before data is entered?
validate="false" ..
The simplest way is to have two actions. The first one has the job of setting the form data, i.e. a blank registration screen. The second action in our writes the registration data to the database. Struts would take care of invoking the validation and returning the user to the correct screen if validation was not complete.
The EditRegistration action in the struts example application illustrates this:
< action path="/editRegistration">
type="org.apache.struts.webapp.example.EditRegistrationAction"
attribute="registrationForm"
scope="request"
validate="false">


When the /editRegistration action is invoked, a registrationForm is created and added to the request, but its validate method is not called. The default value of the validate attribute is true, so if you do not want an action to trigger form validation, you need to remember to add this attribute and set it to false



Q.Can I have an Action without a form?
Yes. If your Action does not need any data and it does
not need to make any data available to the view or
controller component that it forwards to, it doesn't need
a form. A good example of an Action with no ActionForm is
the LogoffAction in the struts example application:


type="org.apache.struts.webapp.example.LogoffAction">



This action needs no data other than the user's session, which
it can get from the Request, and it doesn't need to prepare any
view elements for display, so it does not need a form.


However, you cannot use the tag without
an ActionForm. Even if you want to use the
tag with a simple Action that does not require input,
the tag will expect you to use some type of ActionForm,
even if it is an empty subclass without any properties.

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

Client side validation : validation-rule.xml (java script code should be in this file and in JSP file
)

Server side Validation :
JSP page - should cointain
< html:errors/ >
Aactionform.validate() method
or
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.
How you will display validation fail errors on jsp page? -
The following tag displays all the errors: < html:errors/ >

Q.How you will make available any Message Resources Definitions file to the Struts Framework Environment?
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through < message-resources / > tag. Example: < message-resources parameter= MessageResources / >



Q.What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld

Q.How you will enable front-end client side validation based on the xml in validation.xml?
Validation Framework-Client Side
Validation Framework provides the functionality to validate the form data. It can be use to validate the data on the client side. Errors will be displayed like java script.

Struts has a class called ValidatorForm in org.apache.struts.validator package. This is a subclass of ActionForm and implements the validate() method. The validate() method invokes the Commons Validator, executes the rules using the two xml files (validator-rules.xml and validation.xml) and generates ActionErrors using the Message Resources defined in the struts-config.xml.
validator-rules.xml :
The validator-rules.xml file defines the Validator definitions available for a given application.
The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
validation.xml File :
The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.


Follow the below steps to setup Validation Framework in Struts (server side validation ).

Step 1. Add validator plugin into struts-config.xml




Step 3. In the JSP page (EmpForm.jsp)- Add onsubmit="return validateempForm(this);" and for Client Side Java Script Validation.

<%@ 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" %>


// this is for error message from resource bundle in JSP


Save






Step 4. Add Message Resources location in struts-config.xml



Step 5. In the the Resource Bundle. application_resource.properties file //Here you can add localization.

label.firstName=First Name
label.lastName=Last Name
errors.required={0} is required.


Step 7. In the EmpForm

package com.techfaq.form;
public class EmpForm extends ValidatorForm {
int empId;
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}

Step 6. In the validation.xml - The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application














Step 6. In the validator-rules.xml - The validator-rules.xml file defines the Validator definitions available for a given application.



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




Step 5. Add Action mapping and form entry into the stuts-confix.xml and validate="true" is for validation framework to validate the form input.


"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">





type="com.techfaq.action.EmpAction"
name="EmpForm"
scope="request"
validate="true" // This need for validation framework to validate the form input
input="EmpForm.jsp">
path="success.jsp"/>






Now in the browser type http://localhost:8080/testApp/EmpForm.jsp

Don't Enter firstName and lastName in the text box and submit the "Save" BUTTON. the RequestProcessor checks for the validateattribute in the ActionMapping.
If the validate is set to true, the RequestProcessor invokes the validate() method of the ValidatorForm instance.
If Validate fail the RequestProcessor looks for the input attribute and return to JSP page mentioned in input tag.
If Validate pass goto Action Class execute() method..
If Validate fail , In the browser (EmpForm.jsp) you can see. Java Script pop up Message:


First Name is required.
Last Name is required.


In the empForm firstName and lastName are the required filed. So in the above configuration you can see we add for both firstName and lastName. You can see depends="required" - "required" property is defind in validator-rules.xml. In the resource bundle : application_resource.propertis file
label.firstName=First Name
label.lastName=Last Name
#Error messages used by the Validator
errors.required={0} is required.
{0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind
. and .

Q.What design patterns are used in Struts?
Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.

Service to Worker
Dispatcher View
Composite View (Struts Tiles)
Front Controller
View Helper
Synchronizer Token

Q.What is role of Action Class?
An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

In the execute() method of Action class the business logic is executed.


public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ;


execute() method of Action class:

Perform the processing required to deal with this request
Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
Return an appropriate ActionForward object

Q.What is ActionMapping and is the Action Mapping specified?
Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file






Q.What is the ActionForm and what are important methods in ActionForm?
ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

The important methods of ActionForm are : validate() & reset().

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

Q.What is role of ActionServlet?
ActionServlet 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,
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

Q.What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework 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.



Struts Flow start with ActionServlet then call to process() method of RequestProcessor.



Step 1. Load ActionServlet using load-on-startup and do the following tasks.



Any struts web application contain the ActionServlet configuration in web.xml file.

On load-on-startup the servlet container Instantiate the ActionServlet .

First Task by ActionServlet : The ActionServlet takes the Struts Config file name as an init-param.

At startup, in the init() method, the ActionServlet reads the Struts Config file and load into memory.

Second Task by ActionServlet : If the user types http://localhost:8080/app/submitForm.do in the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the URL has a pattern *.do, with a suffix of "do". Because servlet-mapping is



action

*.do



Third Task by ActionServlet : Then ActionServlet delegates the request handling to another class called RequestProcessor by invoking its process() method.



Step 2. ActionServlet calls process() method of RequestProcessor

What are the components of Struts?
Struts components can be categorize into Model, View and Controller:

Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

What is MVC and how it maps to Struts?
Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.


Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
Action class in struts.

View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
JSP in struts

Controller:The controller reacts to the user input. It creates and sets the model.
ActionServlet and RequestProcessor class in struts.

How do you get a password field in struts ?


Q.Struts Flow In Depth?
Steps 1.
ActionServlet
The central component of the Struts Controller is the ActionServlet. It is
a concrete class and extends the javax.servlet.HttpServlet. It performs
two important things.
On startup, its reads the Struts Configuration file and loads it into memory in
the init() method.
In the doGet() and doPost() methods, it intercepts HTTP request and
handles it appropriately.

In the web.xml


action
org.apache.struts.action.ActionServlet


config
/WEB-INF/struts-config.xml

1



action
*.do


If the user types http://localhost:8080/App1/submitDetails.do in the
browser URL bar. Server will call ActionServlet class because in the url-pattern the mapping is
*.do. Any *.do will call ActionServlet class.
ActionServlet calls the process() method of RequestProcessor class

Step 2.
ActionServlet calls the process() method of RequestProcessor class.
The RequestProcessor first retrieves appropriate XML block for
the URL from struts-config.xml. This XML block is referred to as
ActionMapping in Struts terminology. In fact there is a class called
ActionMapping in org.apache.struts.action package.
ActionMapping is the class that does what its name says ? it holds the mapping
between a URL and Action.

A sample ActionMapping from struts-config.xml

type="mybank.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="CustomerDetailForm.jsp">
path="ThankYou.jsp"
redirect=?true?/>



Step 3.

The RequestProcessor looks up the configuration file for the URL
pattern /submitDetails. and finds the XML block (ActionMapping) shown above.
The type attribute tells Struts which Action class has to be instantiated.

Step 4.
The RequestProcessor instantiates the CustomerForm and puts
it in appropriate scope ? either session or request. The RequestProcessor
determines the appropriate scope by looking at the scope attribute in the same
ActionMapping.

Step 5.
Next, RequestProcessor iterates through the HTTP request parameters
and populates the CustomerForm properties of the same name as the HTTP
request parameters using Java Introspection.

Step 6.
Next, the RequestProcessor checks for the validate attribute in the
ActionMapping. If the validate is set to true, the RequestProcessor invokes
the validate() method on the CustomerForm instance. This is the method
where you can put all the html form data validations. If any error then
RequestProcessor checks for the input attribute in the ActionMapping
and forward to page mentioned in the input tag.
If no error in validate() method then continue.

Step 7.

The RequestProcessor instantiates the Action class specified in the
ActionMapping (CustomerAction) and invokes the execute() method on
the CustomerAction instance. The signature of the execute method is as
follows.
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception

The execute() method returns ActionForward.

ActionForward forward = mapping.findForward(?success?);
return forward. will forward to ThankYou.jsp.
ActionForward forward = mapping.findForward(failure);
return forward. will forward to error.jsp.

Q.How does validate() method of ActionForm work ?
type="mybank.example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="CustomerDetailForm.jsp">
path="ThankYou.jsp"
redirect=?true?/>



RequestProcessor checks for the validate attribute in the
ActionMapping. If the validate is set to true, the RequestProcessor invokes
the validate() method on the CustomerForm instance. This is the method
where you can put all the html form data validations. If any error then
RequestProcessor checks for the input attribute in the ActionMapping
and forward to page mentioned in the input tag.
If no error in validate() method then continue.

and Validate() method looks like
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request)
{
// Perform validator framework validations
ActionErrors errors = new ActionErrors();
// Only need crossfield validations here
if (parent == null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform"));
}
if (firstName == null) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.firstName.null"));
}
return errors;
}

where error.custform and error.firstName.null keys from Message Resource Bundle.

Q.What are the important sections in Struts Configuration File ? struts-config.xml?
The five important sections are:
1. Form bean definition section
2. Global forward definition section
3. Action mapping definition section
4. Controller configuration section
5. Application Resources definition section












type="example.CustomerAction"
name="CustomerForm"
scope="request"
validate="true"
input="/CustomerDetailForm.jsp">








Q.How to handle Handling multiple buttons in HTML Form ?
You have to use a variation of the as shown below to tackle this problem.









In the Message Resource

button.save = Save Me;
button.delete = Delete


you have to add a variable named ?step? in the ActionForm and then add
two methods getStep() and setStep()

In the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{

CustomerForm custForm = (CustomerForm) form;
ActionForward forward = null;
if ( ?Save Me?.equals(custForm.getStep()) ) {
System.out.println(?Save Me Button Clicked?);
} else if(?Delete?.equals(custForm.getStep()) ){
System.out.println(?Delete Button Clicked?);
}
return forward;
}

Q.How does Value replacement in Message Resource Bundle work?
In the resource bundle file, you can define a template like:
errors.required={0} is required.
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.custform","First Name"));

Then the Error message is : First Name is required.

Other constructors are

public ActionError(String key, Object value0, Object value1)
. . .
public ActionError(String key, Object[] values);

What is SwitchAction?
The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application and multiple struts-config.xml. The SwitchAction class can be used as is, without extending.


What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

Details :

LookupDispatchAction is subclass of DispatchAction.
In case of DispatchAction, you have to declare the method name in the JSP page.
For Example :
http://localhost:8080/emp/empaction.do?step=add // IN CASE OF DispatchAction
here step=add , we are delaring method name in JSP.
or
Add //IN CASE OF DispatchAction
so we can't use localization for button.


To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.

In the LookupDispatchAction :
For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. LookupDispatchAction is the answer to this
problem. With LookupDispatchAction, you can combine all three Actions into one.

Example :
Step 1.
three buttons might be










//No need method name declaration in JSP . Button name from resource bundle.

Step 2.
In the the Resource Bundle. //Here you can add localization.
button.add=Add
button.delete=Delete
button.update=Update

Step 3.
Implement a method named getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method returns a java.util.Map. The
keys used in the Map should be also used as keys in Message Resource
Bundle.

public class EmpAction extends LookupDispatchAction {

public Map getKeyMethodMap()
{
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
map.put("button.update", "update");
}


public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("add-success");
}

public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("delete-success");
}

public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("update-success");
}

}

in struts-config.xml

input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
path="addEmpSuccess.jsp"
redirect="true"/>
path="deleteEmpSuccess.jsp"
redirect="true"/>
path="updateEmpSuccess.jsp"
redirect="true"/>


for every form submission, LookupDispatchAction does the
reverse lookup on the resource bundle to get the key and then gets the method
whose name is associated with the key from
getKeyMethodmap().


Flow of LookupDispatchAction:
a) Form the button name "Add" get the key "button.add" fro resource bundle.
b) then in the Map getKeyMethodMap() find the value associated with the key "button.add".
c) value from the Map is "add" . then call add() method of the same action class.

What is the use of LookupDispatchAction?
LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

What is LookupDispatchAction?
The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.


What is the difference between ForwardAction and IncludeAction?
The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

What is IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

IncludeAction included resulting resource in the HTTP response .
In the JSP which don't use struts for include we do


In struts JSP


In the struts-config.xml
parameter="/test/ServletA"
type="org.apache.struts.actions.IncludeAction" />

What is the use of ForwardAction?
The ForwardAction class is useful when you?re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don?t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction

What is DispatchAction?

The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:

ForwardAction
IncludeAction
DispatchAction
LookupDispatchAction
SwitchAction

What is the difference between session scope and request scope when saving formbean ?
when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.

Can we have more than one struts-config.xml file for a single Struts application?
Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:



action org.apache.struts.action.ActionServlet

config
/WEB-INF/struts-config1.xml, /WEB-INF/struts-config2.xml, /WEB-INF/struts-config3




In which method of Action class the business logic is executed ?
In the execute() method of Action class the business logic is executed.


public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception ;


execute() method of Action class:

Perform the processing required to deal with this request
Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
Return an appropriate ActionForward object

What is role of 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.

An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it.

Then the struts controller (ActionServlet) slects an appropriate Action and Request Processor creates an instance if necessary,

and finally calls execute method of Action class.

To use the Action, we need to Subclass and overwrite the execute() method. and your bussiness login in execute() method.

The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the JSP as per the value of the returned ActionForward object.

ActionForward JSP from struts_config.xml file.



Developing our Action Class :



Our Action class (EmpAction.java) is simple class that only forwards the success.jsp.

Our Action class returns the ActionForward called "success", which is defined in the struts-config.xml file (action mapping is show later in this page).

Here is code of our Action Class

public class EmpAction extends Action

{

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception{

return mapping.findForward("success");

}

}



mapping.findForward("success"); forward to JSP mentioned in struts_config.xml.

struts_config.xml configuration is :




path="/EmpAction"

type="com.techfaq.EmpAction">





mapping.findForward("success") method forward to success.jsp (mentioned in struts_config.xml);





Here is the signature of the execute() method Action Class.



public ActionForward execute(ActionMapping mapping,

ActionForm form,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)

throws java.lang.Exception



Where

mapping - The ActionMapping used to select this instance

form - The optional ActionForm bean for this request (if any)

request - The HTTP request we are processing

response - The HTTP response we are creating

Throws:

Action class throws java.lang.Exception - if the application business logic throws an exception



In the browser : http://localhost:8080/testApp/EmpAction.do

This will call to execute() method of EmpAction and after that based on mapping.findForward("success") forward to success.jsp.

How is the Action Mapping specified ?
We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from configuration element of struts-config.xml file





What is ActionMapping?
ActionMapping object contains all the mapping information in struts_config.xml.

ActionServlet create the instance of ActionMapping and load all the struts_config.xml data to ActionMapping object.

Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

ActionMapping object contains all the mapping information in struts_config.xml.

For Example :


type="com.techfaq.action.EmpAction"
name="EmpForm"
scope="request"
validate="true" // This need for validation framework to validate the form input
input="EmpForm.jsp">
path="success.jsp"/>




Describe validate() and reset() methods ?
validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

ActionErrors errors = new ActionErrors();
if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required"));
}
return errors;
}

You have to add the error key from resource bundle.

error.usernamepassword.required : key from resource bundle properties file.

In the JSP , you have to add the below tag to display the error message from validate() method.



reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

Example :
public void reset(ActionMapping mapping, HttpServletRequest request) {

this.password = null;
this.username = null;
}

Set null for every request.

What is role of ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework 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.



Struts Flow start with ActionServlet then call to process() method of RequestProcessor.



Step 1. Load ActionServlet using load-on-startup and do the following tasks.



Any struts web application contain the ActionServlet configuration in web.xml file.

On load-on-startup the servlet container Instantiate the ActionServlet .

First Task by ActionServlet : The ActionServlet takes the Struts Config file name as an init-param.

At startup, in the init() method, the ActionServlet reads the Struts Config file and load into memory.

Second Task by ActionServlet : If the user types http://localhost:8080/app/submitForm.do in the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the URL has a pattern *.do, with a suffix of "do". Because servlet-mapping is



action

*.do



Third Task by ActionServlet : Then ActionServlet delegates the request handling to another class called RequestProcessor by invoking its process() method.



Step 2. ActionServlet calls process() method of RequestProcessor

What are the core classes of the Struts Framework?
Struts follow Model View Controller Architecture. Components is divided based on MVC.

Controller :

The ActionServlet and the collaborating classes are RequestProcessor, ActionForm, Action, ActionMapping and ActionForward in in Controller category.

ActionServlet :

The central component of the Struts Controller is the ActionServlet. It is a concrete class and extends the javax.servlet.HttpServlet. It performs two important things.
1. On startup, its reads the Struts Configuration file and loads it into memory in the init() method.
2. In the doGet() and doPost() methods, it intercepts HTTP request and handles it appropriately.


View :

The View category contains utility classes ? variety of custom tags (html,bean,logic) and JSP.

Model :

Struts does not offer any components in the Model Category. Your Action class contains business logic may be model.

What are the components of Struts?
Struts and Model View Controller (MVC)
Struts follow Model View Controller Architecture. Components is divided based on MVC.

Controller :

The ActionServlet and the collaborating classes are RequestProcessor, ActionForm, Action, ActionMapping and ActionForward in in Controller category.

ActionServlet :

The central component of the Struts Controller is the ActionServlet. It is a concrete class and extends the javax.servlet.HttpServlet. It performs two important things.
1. On startup, its reads the Struts Configuration file and loads it into memory in the init() method.
2. In the doGet() and doPost() methods, it intercepts HTTP request and handles it appropriately.


View :

The View category contains utility classes ? variety of custom tags (html,bean,logic) and JSP.

Model :

Struts does not offer any components in the Model Category. Your Action class contains business logic may be model.

How you will enable front-end validation based on the xml in validation.xml?
The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form \"loginForm\" as defined in the validation.xml file. The 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:


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 Struts Validator Framework?


Validation Framework provides the functionality to validate the form data. It can be use to validate the data on the client side as well as on the server side.

Struts has a class called ValidatorForm in org.apache.struts.validator package. This is a subclass of ActionForm and implements the validate() method. The validate() method invokes the Commons Validator, executes the rules using the two xml files (validator-rules.xml and validation.xml) and generates ActionErrors using the Message Resources defined in the struts-config.xml.
validator-rules.xml :
The validator-rules.xml file defines the Validator definitions available for a given application.
The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
validation.xml File :
The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.


Follow the below steps to setup Validation Framework in Struts (server side validation ).

Step 1. Add validator plugin into struts-config.xml




Step 3. In the JSP page (EmpForm.jsp)- add

<%@ 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" %>


// this is for error message from resource bundle in JSP


Save



Step 4. Add Message Resources location in struts-config.xml



Step 5. In the the Resource Bundle. application_resource.properties file //Here you can add localization.

label.firstName=First Name
label.lastName=Last Name
errors.required={0} is required.


Step 7. In the EmpForm

package com.techfaq.form;
public class EmpForm extends ValidatorForm {
int empId;
String firstName;
String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
}

Step 6. In the validation.xml - The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application














Step 6. In the validator-rules.xml - The validator-rules.xml file defines the Validator definitions available for a given application.



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




Step 5. Add Action mapping and form entry into the stuts-confix.xml and validate="true" is for validation framework to validate the form input.


"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">





type="com.techfaq.action.EmpAction"
name="empForm"
scope="request"
validate="true" // This need for validation framework to validate the form input
input="EmpForm.jsp">
path="success.jsp"/>






Now in the browser type http://localhost:8080/testApp/EmpForm.jsp

Don't Enter firstName and lastName in the text box and submit the "Save" BUTTON. the RequestProcessor checks for the validateattribute in the ActionMapping.
If the validate is set to true, the RequestProcessor invokes the validate() method of the ValidatorForm instance.
If Validate fail the RequestProcessor looks for the input attribute and return to JSP page mentioned in input tag.
If Validate pass goto Action Class execute() method..
If Validate fail , In the browser (EmpForm.jsp) you can see. In red color.


First Name is required.
Last Name is required.


In the empForm firstName and lastName are the required filed. So in the above configuration you can see we add for both firstName and lastName. You can see depends="required" - "required" property is defind in validator-rules.xml. In the resource bundle : application_resource.propertis file
label.firstName=First Name
label.lastName=Last Name
#Error messages used by the Validator
errors.required={0} is required.
{0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind
. and .

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 (by RequestProcessor)on the server side with data entered from a form on the client side.

If your JSP contain two fields
username and password



Then the ActionForm is
public class LogonForm extends ActionForm{

/**
* Password entered by user
*/
private String password = null;
/**
* Username entered by user
*/
private String username = null;
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @param password The password to set.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return Returns the username.
*/
public String getUsername() {
return username;
}
/**
* @param username The username to set.
*/
public void setUsername(String username) {
this.username = username;
}
}

When you enter data to your JSP and submit the request processor set the data to LogonForm. You don't need to do request.getParameter("username") etc,

What is 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.

An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it.

Then the struts controller (ActionServlet) slects an appropriate Action and Request Processor creates an instance if necessary,

and finally calls execute method of Action class.

To use the Action, we need to Subclass and overwrite the execute() method. and your bussiness login in execute() method.

The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the JSP as per the value of the returned ActionForward object.

ActionForward JSP from struts_config.xml file.



Developing our Action Class :



Our Action class (EmpAction.java) is simple class that only forwards the success.jsp.

Our Action class returns the ActionForward called "success", which is defined in the struts-config.xml file (action mapping is show later in this page).

Here is code of our Action Class

public class EmpAction extends Action

{

public ActionForward execute(

ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response) throws Exception{

return mapping.findForward("success");

}

}



mapping.findForward("success"); forward to JSP mentioned in struts_config.xml.

struts_config.xml configuration is :




path="/EmpAction"

type="com.techfaq.EmpAction">





mapping.findForward("success") method forward to success.jsp (mentioned in struts_config.xml);





Here is the signature of the execute() method Action Class.



public ActionForward execute(ActionMapping mapping,

ActionForm form,

javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response)

throws java.lang.Exception



Where

mapping - The ActionMapping used to select this instance

form - The optional ActionForm bean for this request (if any)

request - The HTTP request we are processing

response - The HTTP response we are creating

Throws:

Action class throws java.lang.Exception - if the application business logic throws an exception



In the browser : http://localhost:8080/testApp/EmpAction.do

This will call to execute() method of EmpAction and after that based on mapping.findForward("success") forward to success.jsp.

How you will make available any Message Resources Definitions file to the Struts Framework Environment?
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag.
Example:



application_resource is properties file.

application_resource.properties looks like
error.vendor.location =
  • Error at Vendor Location.
    error.Recordingurl.needed =
  • URL is Mandatory for Other Vendor.

    What is ActionServlet?
    The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework 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.

    Struts Flow start with ActionServlet then call to process() method of RequestProcessor.

    Step 1. Load ActionServlet using load-on-startup and do the following tasks.

    Any struts web application contain the ActionServlet configuration in web.xml file.
    On load-on-startup the servlet container Instantiate the ActionServlet .
    First Task by ActionServlet : The ActionServlet takes the Struts Config file name as an init-param.
    At startup, in the init() method, the ActionServlet reads the Struts Config file and load into memory.
    Second Task by ActionServlet : If the user types http://localhost:8080/app/submitForm.do in the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the URL has a pattern *.do, with a suffix of "do". Because servlet-mapping is

    action
    *.do

    Third Task by ActionServlet : Then ActionServlet delegates the request handling to another class called RequestProcessor by invoking its process() method.

    Step 2. ActionServlet calls process() method of RequestProcessor



    Q.How you will display validation fail errors on jsp page?
    Add to your jsp page.

    validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {

    ActionErrors errors = new ActionErrors();
    if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
    errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required"));
    }
    return errors;
    }

    You have to add the error key from resource bundle.

    error.usernamepassword.required : key from resource bundle properties file.

    In the JSP , you have to add the below tag to display the error message from validate() method.


    Q.How you will enable front-end client validation based on the xml in validation.xml?
    The tag to allow front-end validation based on the xml in validation.xml.

    Validation Framework provides the functionality to validate the form data. It can be use to validate the data on the client side. Errors will be displayed like java script.

    Struts has a class called ValidatorForm in org.apache.struts.validator package. This is a subclass of ActionForm and implements the validate() method. The validate() method invokes the Commons Validator, executes the rules using the two xml files (validator-rules.xml and validation.xml) and generates ActionErrors using the Message Resources defined in the struts-config.xml.
    validator-rules.xml :
    The validator-rules.xml file defines the Validator definitions available for a given application.
    The validator-rules.xml file acts as a template, defining all of the possible Validators that are available to an application.
    validation.xml File :
    The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application.


    Follow the below steps to setup Validation Framework in Struts (server side validation ).

    Step 1. Add validator plugin into struts-config.xml




    Step 3. In the JSP page (EmpForm.jsp)- Add onsubmit="return validateempForm(this);" and for Client Side Java Script Validation.

    <%@ 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" %>


    // this is for error message from resource bundle in JSP


    Save






    Step 4. Add Message Resources location in struts-config.xml



    Step 5. In the the Resource Bundle. application_resource.properties file //Here you can add localization.

    label.firstName=First Name
    label.lastName=Last Name
    errors.required={0} is required.


    Step 7. In the EmpForm

    package com.techfaq.form;
    public class EmpForm extends ValidatorForm {
    int empId;
    String firstName;
    String lastName;
    public String getFirstName() {
    return firstName;
    }
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    public String getLastName() {
    return lastName;
    }
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }
    public int getEmpId() {
    return empId;
    }
    public void setEmpId(int empId) {
    this.empId = empId;
    }
    }

    Step 6. In the validation.xml - The validation.xml file is where you couple the individual Validators defined in the validator-rules.xml to components within your application














    Step 6. In the validator-rules.xml - The validator-rules.xml file defines the Validator definitions available for a given application.



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




    Step 5. Add Action mapping and form entry into the stuts-confix.xml and validate="true" is for validation framework to validate the form input.


    "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">





    type="com.techfaq.action.EmpAction"
    name="EmpForm"
    scope="request"
    validate="true" // This need for validation framework to validate the form input
    input="EmpForm.jsp">
    path="success.jsp"/>






    Now in the browser type http://localhost:8080/testApp/EmpForm.jsp

    Don't Enter firstName and lastName in the text box and submit the "Save" BUTTON. the RequestProcessor checks for the validateattribute in the ActionMapping.
    If the validate is set to true, the RequestProcessor invokes the validate() method of the ValidatorForm instance.
    If Validate fail the RequestProcessor looks for the input attribute and return to JSP page mentioned in input tag.
    If Validate pass goto Action Class execute() method..
    If Validate fail , In the browser (EmpForm.jsp) you can see. Java Script pop up Message:


    First Name is required.
    Last Name is required.


    In the empForm firstName and lastName are the required filed. So in the above configuration you can see we add for both firstName and lastName. You can see depends="required" - "required" property is defind in validator-rules.xml. In the resource bundle : application_resource.propertis file
    label.firstName=First Name
    label.lastName=Last Name
    #Error messages used by the Validator
    errors.required={0} is required.
    {0} will be filled by (First Name or Last Name) because validation.xml above configuration you have defind
    . and .

  • No comments: