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 :
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
For Example : (( If RuntimeException in SaveEmpAaction class , control goes to exception.jsp)
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 ?
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
You have to add
Step 2.
Add action mapping in struts-config.xml
type="empForm"
name="AddressForm"
scope="request"
validate="true"
input="/empform.jsp">
and add the form bean inside
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 :
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
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
type="com.techfaq.form.FileUploadForm"/>
Step 3.
add action mapping entry in the struts-config.xml file:
type="com.techfaq.action.FileUploadAndSaveAction"
name="FileUploadForm"
scope="request"
validate="true"
input="/pages/fileupload.jsp">
Step 4.
In the JSP
File Name
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
Add action mapping in the struts-config.xml file:
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 :
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
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 :
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
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
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
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
redirect="true"/>
redirect="true"/>
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
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
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
redirect="true"/>
redirect="true"/>
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
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
redirect="true"/>
redirect="true"/>
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
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
in the struts-config.xml
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:
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:
_ Next, add an ActionMapping in the Struts Config file as follows:
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
In the Java Script
Integration Struts Spring Hibernate ?
Code is here with explanation
Step 1.
In the struts-config.xml add plugin
Step 2.
In the applicationContext.xml file
Configure datasourse
Step 3.
Configure SessionFactory
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" %>
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:
No comments:
Post a Comment