Uploading Files with Actions in struts

In this post, We will discuss how to allow the user to upload a file using Struts framework. to enable the user to upload a file,We need to set the encoding type of html:form tag to "multipart/form-data" and specify the HTTP method as "post".The property file in the FileUploadForm is of type org.apache.struts.upload.FormFile. 
Create upload.jsp :-

<html>
   <head>
   <title> Upload File</title>  
 </head>
   <body>
   <html:errors />
     <html:form action="/FileUploadUpdate" method="post" enctype="multipart/form-data">
     Select File : <html:file property="userfile" />
<br/>
     <html:submit />
     </html:form>
   </body>
</html>

Now Create FileUploadAction class :-

package WiseDeveloper.co.in;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.upload.FormFile;
public class FileUploadAction extends org.apache.struts.action.Action { 
    private final static String Key = "success";   
public ActionForward execute(ActionMapping mapping, ActionForm form,  HttpServletRequest request, HttpServletResponse response)   throws Exception {   
    ImageUploadForm uploadForm = (ImageUploadForm) form;       
FileOutputStream outputStream = null;       
FormFile formFile = null; 
      try {            formFile = uploadForm.getFile();     
      String path = getServlet().getServletContext().getRealPath("")+"/"+ formFile.getFileName();   
        outputStream = new FileOutputStream(new File(path));   
        outputStream.write(formFile.getFileData());     
  }
finally {            if (outputStream != null) {     
          outputStream.close();         
  }       
}       
uploadForm.setMessage("The File is uploaded successfully.");       
return mapping.findForward(Key);   
}
}

Action Methods into struts

An Action is class that mediator between an incoming request and the corresponding business logic.The controller will create an instance for each request (if necessary), and call the execute method. 
org.apache.struts.action.Action class have many method :-
Exception  if the application business logic throws an exception.
public 
ActionForward   execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) 
public ActionForward execute(ActionMapping mapping,ActionForm form,  HttpServletRequest request, HttpServletResponse response)      throws Exception
  
2. addErrors() :-
-protected void addErrors(HttpServletRequest request,  ActionMessages errors)
3. addMessages() :-
-protected void addMessages(HttpServletRequest request,
                           ActionMessages messages)
saveToken and istokenValid is the helper methods which enable you to add advanced functionality toyour struts application. saveToken and istokenValid both is to make sure that a form has not submitted twice.
In struts applicaion,transaction tokens to ensure that a form is not submitted twice.A transaction is unique string that is generated.The token is submitted with the form tag.
saveToken :
isTokenvalid
why we are using this concept :-We send the request to the server for first time it is going to accept it and if we are sending multiple requests as like that then from second request onwards it stops executing the code.So only first request only it works.
In bank applications if we send multiple times then improper action occurs and we may get unrelated problems.
Action isCancelled into struts
Struts provides a special input field called html:cancel.You can use this input field to cancel a form submission.when you use the isCancelled method in the action handler to see whether the action was cancelled.
Syntax of isCancelled method :-             protected  boolean isCancelled(HttpServletRequest request)
This method return the boolean value. if the current form's cancel button was pressed then return true otherwise  return false.
Create the input form :-login.jsp


<html:form  action="Loginaction" >
<html:text property="User name"/>
<html:password property="password"/>
<html:submit/>
<html:cancel/>
</html:form>

Create Actionhandler class :-
 


package r4r.co.in;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse respose)throws Exception {
return add(mapping,form,request,respose); }
public ActionForward add(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse respose)throws Exception{ 
if(isCancelled(request)) {
System.out.println("This submission has been cancelled ::"); 
  return (mapping.findForward("home");     }
else if(isTokenValid(request)) {
LoginForm form1=(LoginForm)form;
return mapping.findForward("success"); }
else {
System.out.println("User can't submit the same form ");
return mapping.findForward("resubmit");
}
}

Action getLocale and setLocale into struts
Struts 1.3 supports the functionality of retrieving and changing the current locale settings.You can dynamically set the Locale for the user's session.GetLocale() and SetLocale() method are the helper of Action class.
 
GetLocale():- 
                  protected  Locale getLocale(HttpServletRequest request)  SetLocale() :-
                      protected  void setLocale(HttpServletRequest request, Locale locale)          
Example :-
 
 
Action saveMessages and getResources into struts
 saveMessages
Working with ActionMessages and ActionErrors is nearly identical but only difference is that the <html:errors> tag forced you to place HTML in the message resource file.This is not good. 
In <html:messages> tag, We can sets up a loop where you may easily stick in the HTML you want.
This forces <html:messages> to get the messages from Globals.MESSAGE_KEY in request scope. (if messages="true" is set), if any messages are required.


<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html:messages id="msg" message="true">
<bean:write name="msg"/>
<br></html:messages>  

 
saveMessages :- 
Syntex of this method :-              protected  void saveMessages(HttpServletRequest request, ActionMessages messages) 
              protected  void saveMessages(HttpSession session, ActionMessages messages) 
        
getResources :-
Syntex of this method :-
                   protected  MessageResources getResources(HttpServletRequest request) :-
                  protected  MessageResources getResources(HttpServletRequest request, String key):- 
This method will return the specified message resources for the current locale.
This method
will return the default message resources for the current locale.
This method is used to get number of messages resources for that locale.
  This method save the specified messages keys into the appropriate request or session attribute for use by the <html:messages> tag.
and getResources method helper methods of Action into struts framework.ActionMessages to display dynamic i18n-enabled messages.
ATM machine,The First thing it often asks you is what language you speak,and press appropriate button.You could do the same thing for your site.
This is used to sets the locale to the new specified locale.Globals.LOCALE_KEY stores the  user's currently selected Locale into their HttpSession scope.
This methods returns the current selected locale on the client machine.
:- This method return true or false value.This method return 'true' if the token stored in the session with that submitted from the form  both are equals otherwise return false. 
-This method generates a unique token and saves it token in the session under the key org.apache.struts.action.TOKEN. 
This method is used to adds the specified messages keys into the appropriate request  attribute.
This method is used to adds the specified errors keys into the appropriate request attribute


1.execute() :-If The response has been completed then forward to which control should be transferred.This method throws an
Exception  if the application business logic throws an exception.
public 
ActionForward   execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) 
public ActionForward execute(ActionMapping mapping,ActionForm form,  HttpServletRequest request, HttpServletResponse response)      throws Exception
  
2. addErrors() :-
-protected void addErrors(HttpServletRequest request,  ActionMessages errors)
3. addMessages() :-
-protected void addMessages(HttpServletRequest request,
                           ActionMessages messages)
Action saveToken and isTokenValid into struts
saveToken and istokenValid is the helper methods which enable you to add advanced functionality toyour struts application. saveToken and istokenValid both is to make sure that a form has not submitted twice.
In struts applicaion,transaction tokens to ensure that a form is not submitted twice.A transaction is unique string that is generated.The token is submitted with the form tag.
saveToken :
isTokenvalid
why we are using this concept :-We send the request to the server for first time it is going to accept it and if we are sending multiple requests as like that then from second request onwards it stops executing the code.So only first request only it works.
In bank applications if we send multiple times then improper action occurs and we may get unrelated problems.
Action isCancelled into struts
Struts provides a special input field called html:cancel.You can use this input field to cancel a form submission.when you use the isCancelled method in the action handler to see whether the action was cancelled.
Syntax of isCancelled method :-             protected  boolean isCancelled(HttpServletRequest request)
This method return the boolean value. if the current form's cancel button was pressed then return true otherwise  return false.
Create the input form :-login.jsp


<html:form  action="Loginaction" >
<html:text property="User name"/>
<html:password property="password"/>
<html:submit/>
<html:cancel/>
</html:form>

Create Actionhandler class :-
 


package r4r.co.in;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends Action{
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse respose)throws Exception {
return add(mapping,form,request,respose); }
public ActionForward add(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse respose)throws Exception{ 
if(isCancelled(request)) {
System.out.println("This submission has been cancelled ::"); 
  return (mapping.findForward("home");     }
else if(isTokenValid(request)) {
LoginForm form1=(LoginForm)form;
return mapping.findForward("success"); }
else {
System.out.println("User can't submit the same form ");
return mapping.findForward("resubmit");
}
}

Action getLocale and setLocale into struts
Struts 1.3 supports the functionality of retrieving and changing the current locale settings.You can dynamically set the Locale for the user's session.GetLocale() and SetLocale() method are the helper of Action class.
 
GetLocale():- 
                  protected  Locale getLocale(HttpServletRequest request)  SetLocale() :-
                      protected  void setLocale(HttpServletRequest request, Locale locale)          
Example :-
 
 
Action saveMessages and getResources into struts
 saveMessages
Working with ActionMessages and ActionErrors is nearly identical but only difference is that the <html:errors> tag forced you to place HTML in the message resource file.This is not good. 
In <html:messages> tag, We can sets up a loop where you may easily stick in the HTML you want.
This forces <html:messages> to get the messages from Globals.MESSAGE_KEY in request scope. (if messages="true" is set), if any messages are required.


<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html:messages id="msg" message="true">
<bean:write name="msg"/>
<br></html:messages>  

 
saveMessages :- 
Syntex of this method :-              protected  void saveMessages(HttpServletRequest request, ActionMessages messages) 
              protected  void saveMessages(HttpSession session, ActionMessages messages) 
        
getResources :-
Syntex of this method :-
                   protected  MessageResources getResources(HttpServletRequest request) :-
                  protected  MessageResources getResources(HttpServletRequest request, String key):- 
 
This method will return the specified message resources for the current locale.
This method
will return the default message resources for the current locale.
This method is used to get number of messages resources for that locale.
  This method save the specified messages keys into the appropriate request or session attribute for use by the <html:messages> tag.
and getResources method helper methods of Action into struts framework.ActionMessages to display dynamic i18n-enabled messages.
ATM machine,The First thing it often asks you is what language you speak,and press appropriate button.You could do the same thing for your site.
This is used to sets the locale to the new specified locale.Globals.LOCALE_KEY stores the  user's currently selected Locale into their HttpSession scope.
This methods returns the current selected locale on the client machine.
:- This method return true or false value.This method return 'true' if the token stored in the session with that submitted from the form  both are equals otherwise return false. 
-This method generates a unique token and saves it token in the session under the key org.apache.struts.action.TOKEN. 
This method is used to adds the specified messages keys into the appropriate request  attribute.
This method is used to adds the specified errors keys into the appropriate request attribute
Action saveToken and isTokenValid into struts

Action Types and How to Use

ForwardAction acts as bridge from the current view and pages it link to.ForwardAction uses the RequestDispatcher to forward to a specified web resource.This allow you to link to an action instead of directly to a jsp.
The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. 
 ForwardAction used 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.
Following step are required in ForwardAction :-1
<html::link action="home">Login </html:link>
2.Create an action mapping that uses  the ForwardAction with the parameter attributes to specify the jsp pages.
 
 ForwardAction are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime.
The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.
<action path="/home" type="org.apache.struts.action.ForwardAction" parameter="home.jsp"/>
Thee mapping of action forward  can be specified in a global section. It independent of any specific action mapping.
<global-forwards>
<forward name="Success" path="success.jsp" />
<forward name="Failure" path="index.jsp" />
</global-forward>
 
IncludeAction
IncludeAction is similar the ForwardAction but only difference is that you need to use the IncludeAction only if the action is going to be included by another jsp.
 Used of Include Action :-1. IncludeAction class  to include another resource in the response to the request being processed.
2. IncludeAction class is useful when you want to integrate Struts into an application.
Configure IncludeAction into struts-config.xml
We should be configure IncludeAction into struts-config.xml. You must create an action mapping when you want used IncludeAction The parameter attribute specifies the URL that will be included when the specified path is accessed.
Create IncludeAction mapping entries in the Struts configuration file:-<action-mappings>
<action path="/login"
type="org.apache.struts.actions.IncludeAction"
parameter="/login.jsp/>
</action-mappings>
DispatchAction
The DispatchAction class is used to group related action into one class.DispatchAction class is an abstract class.
This class extends the Action class.
You have a method for each logical action. The value of the the incoming request parameter is the name of the method.
There are following step is required  to use DispatchAction :- 
1.
2. 
3.
4.
Create welcome.jsp :-

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html><head>
<title>This is DispatchAction Example World</title>
</head>
<body>
<center>
<h1>
<bean:write name="UserForm" property="message" /></h1>
</center>
 </body>
</html>

 
SourceCode:


package WiseDeveloper.co.in;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
public class UserAction extends DispatchAction {
private final static String SUCCESS = "success";
public ActionForward hindi(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("This is Hindi language.");
return mapping.findForward(SUCCESS);
}
public ActionForward english(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("This is English language.");
return mapping.findForward(SUCCESS);
}
public ActionForward chinese (ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm userForm = (UserForm) form;
userForm.setMessage("This is Chinese language.");
return mapping.findForward(SUCCESS);
}
}


Configure DispatchAction into struts-config.xmlIn this section, Create an action mapping for this action handler using the parameter attributes to specify the request parameter that carries the name of the method you want to invoke. 

SourceCode:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans >
<form-bean name="UserForm" type="WiseDeveloper.co.in.UserForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
<action input="/index.jsp" parameter="method" name="UserForm" path="/UserAction" scope="session" type="WiseDeveloper.co.in.UserAction">
<forward name="success" path="/welcome.jsp" />
</action>
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

 
LookupDispatchAction
LookupDispatchAction class is a subclass of DispatchAction. It does a reverse lookup on the resource bundle.
You have to implement a special method that map to the key and then gets the method whose name is associated with the key into the Resource Bundle. 

   

The comman use of LookupDispatchAction class :-
This class 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.
In the LookupDispatchAction is based on a lookup of a key value but  DispatchAction is specifying the method name directly. 
Create a Action Mapping in struts-config.xml file :-


<action path="/submitlookupDispatchExample" type="WiseDeveloper.co.in.LookupAction"
input="/index.jsp" name="LookupForm" parameter="method" scope="request" validate="true">
<forward name="success' path="success.jsp" />
</action>

 

SourceCode:


package WiseDeveloper.co.in;
public class LookupAction extends LookupDispatchAction {
private final static String key = "success";
protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("LookupForm.add", "add");
map.put("LookupForm.remove", "remove");
return map;
}
public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LookupForm userForm = (LookupForm) form;
LookupForm.setMessage("This is add method.");
return mapping.findForward(key);
}
public ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
LookupForm userForm = (LookupForm) form;
userForm.setMessage("This is remove method.");
return mapping.findForward(key);
}
}

SwitchAction
SwitchAction is useful only if you have multiple modules in your Struts application.The SwitchAction class is used to support switching from module to module.
We can used this class in our appication when We want to switch from a resource in one module to another resource in a different module. 
 
Configure SwitchAction into struts-config.xml
When We want to used switchAction in our application. First create mapping in a switchAction into your struts-config.xml file.
You perforn following step :-
1. 
2

   <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">     
<struts-config>  
  <form-beans > 
    <form-bean name="switchForm" type="WiseDeveloper.co.in.SwitchForm" />
  </form-beans>
    <global-exceptions />
   <global-forwards />
     <action-mappings> 
     <action path="/switch" type="org.apache.struts.actions.SwitchAction"/> 
     <action path="/exampleswitchaction" type="WiseDeveloper.co.in.SwitchAction" name="switchForm" input="/switch.jsp" parameter="method">       
<forward name="sum" path="/switch.do? page=/add.do;prefix=/add" redirect="true"/>   
   <forward name="delete" path="/delete.jsp" redirect="true"/> 
    </action>
      </action-mappings> 
    <message-resources parameter="WiseDeveloper.co.in.ApplicationResources" />
    </struts-config>

 
 
 
Example:-


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>   
<servlet-name>action</servlet-name> 
  <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
   <init-param>   
  <param-name>config</param-name> 
   <param-value>/WEB-INF/struts-config.xml</param-value> 
  </init-param>   
<init-param> 
   <param-name>config/switch</param-name>     
<param-value>/WEB-INF/switch-config.xml</param-value> 
</init-param> 
  <init-param>   
  <param-name>debug</param-name>     
<param-value>3</param-value> 
  </init-param>   
<init-param>   
  <param-name>detail</param-name>     
<param-value>3</param-value>   
</init-param>   
<load-on-startup>0</load-on-startup> 
</servlet> 
<servlet-mapping>
   <servlet-name>action</servlet-name> 
  <url-pattern>*.do</url-pattern> 
</servlet-mapping> 
<welcome-file-list> 
 <welcome-file>switch.jsp</welcome-file> 
</welcome-file-list>
</web-app>

Configure ForwardAction into struts-config.xml

ForwardAction

Session vs. Request Scope

Scope specifies the scope of the form bean that is bound to the describes Action..
You are using request scope the values of form bean would be available for one the current request.One the response has been returned to the client the actionform and the data within it are no langer accessible.but
In the session , the values of form bean would be available throughout the session.

Example :-


<action input="/login.jsp" name="LoginForm" path="/Login" scope="session" type="com.wisedeveloper.LoginAction">
In this example, scope is set session so the values of form bean would be available throughout the session.

What is DynaActionForm?

The Struts DynaActionForm class enables you to create a "virtual" form bean in Struts configuration file instead of create a real Java form bean class. It can avoid you to create many simple but tedious form bean classes.
 DynaActionForm do not  have to write setters and getters. No bean class is required for the DynaActionForm.  
With DynaActionForm, the property access is no different than using request.get Parameter( .. ).
DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

struts-config.xml :-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd"> 
<struts-config>
<form-beans>
<form-bean name="dynaUserForm" type="org.apache.struts.action.DynaActionForm">
   <form-property name="username" type="java.lang.String"/>
</form-bean>
</form-beans>
<action-mappings>
<action path="/Login" type="WiseDeveloper.co.in.UserAction" name="dynaUserForm">
<forward name="success" path="success.jsp"/>
<forward name="failed" path="login.jsp"/>
</action>
</action-mappings>
<message-resources parameter="WiseDeveloper.co.in.ApplicationResource" />
</struts-config>

 

Understanding the Life Cycle of an ActionForm

In this chapter, We will discuss the lifecycle of an ActionForm. ActionForm class maintain the session state of web application.
 ActionForm sits between the View and Controller.ActionForm play the role of transfer object between the presentation layer and  Business  layer.

Life Cycle of an ActionForm:-
1. Request is submitted.The ActionServlet controller matches the URI for the request against the path of an action-mapping.
2. Create or recycle ActionForm
3. The ActionServlet then calls reset() on the new or pre-existing ActionForm from the request.\
4. You can store ActionForm in desired scope
5. When passing ActionForm beans between Actions.It is important to populate ActionForm from Request. If you modify a value, you must be sure to protect it from auto populate or reset.
6. if Validate is set to true,the ActionServlet call the validate method.
7. This return any errors message.then forward back to input attribute page actionForm in scope.If no errors found then call execute() with the ActionForm.
8.  Forward to success 

What is an ActionForm?

An ActionForm is also called JavaBean.When client will enter the data from the form than this object is automatically populated on the server side. 


ActionForm class maintains the session state for web application.The ActionForm class extends from org.apache.struts.action.ActionForm. ActionForm class have getter and setter method. Getter method  is used to get the value from the form and setter method is used to set the value.
Struts Framework provides the functionality to validate the form data. When client enter the input from form if We want to add some validation than We can add the validate() method in the ActionForm class.Error messages are added to the ActionMapping object.
We can be use to validate the data on the users browser as well as on the server side. 

SourceCode:



package com.wisedeveloper.co.in;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
public class LoginForm extends org.apache.struts.action.ActionForm{
               private static final long serialVersionUID = 11112;
               private String username,password;
               public String getPassword() {
                               return password;
               }
               public void setPassword(String password) {
                               this.password = password;
               }
               public String getUsername() {
                               return username;
               }
               public void setUsername(String username) {
                               this.username = username;
               }
               public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
                               ActionErrors errors = new ActionErrors();
                               if (username == null || username.length() < 1) {
                               errors.add("username", new ActionMessage("error.username.required"));
                               }
                               else if (password == null || password.length() < 1) {
                               errors.add("password", new ActionMessage("error.password.required"));
                               }
                              
                               return errors;
               }
               }

JavaBeans and Scope :- Model Components in Struts Frameworks

JavaBeans can be stored a number of different collections of attributes.the rules defining lifetime and visibility are called the scope of those beans.


JavaBeans can be stored a number of different collections of attributes.the rules defining lifetime and visibility are called the scope of those beans.

page - This is used for visible within a single JSP page, for the lifetime of the current request.
request - This is used for visible within a single JSP page, as well as to any page or servlet that is included in this page, or forwarded to by this page. 
session - Thsi are visible to all JSP pages and servlets that participate in a particular user session .This bean handle one or more requests. 
application - This are visible to all JSP pages and servlets that are part of a web application.

ActionForm Beans:- Model Components in Struts Frameworks
ActionForm beans almost similar to the JavaBeans( ModelBeans) but should be consider a Controller component. Because, that able to transfer data between the
Model and View layers.


 In struts framework the ActionForm is generally define by the extending the org.apache.struts.action.ActionForm, Sometime ActionBean also called "form beans". These may be finely-grained objects, so that there is one bean for each form, or coarsely-grained so that one bean serves several forms, or even an entire application.

JavaBeans and Scope :- Model Components in Struts Frameworks

JavaBeans can be stored a number of different collections of attributes.the rules defining lifetime and visibility are called the scope of those beans.


JavaBeans can be stored a number of different collections of attributes.the rules defining lifetime and visibility are called the scope of those beans.

page - This is used for visible within a single JSP page, for the lifetime of the current request.
request - This is used for visible within a single JSP page, as well as to any page or servlet that is included in this page, or forwarded to by this page. 
session - Thsi are visible to all JSP pages and servlets that participate in a particular user session .This bean handle one or more requests. 
application - This are visible to all JSP pages and servlets that are part of a web application.

Display (on JSP) an Object (From the Model) with Struts Tags

Struts provide tags to display model’s objects on JSP page. In this section we will cover it. Action is end point for Struts based application .Action interacts with model after completions of calculations and manipulations Action class will returns a key. On the behalf of this key some control flow operations.


There are following steps to display an object on view:

>>Reconfigure struts-config.xml

Add an attribute (i.e. attribute="user") in  tag that is used to map the ActionForm for into scope (request/session)

Here the attribute maps the Action-Form into a scope (The scope is by default session) under "user". Now ActionForm is set in session scope.So we can display the properties of ActionForm on JSP View .



>> On JSP View:

Import the bean tag library into the JSP as follows:
<%@ taglib uri="/tags/struts-bean" prefix="bean"%>

Use the  tag  to output properties of the ActionForm.
SourceCode:


<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<html>
<head>
<title> World</title>
</head>
<body bgcolor="green">
<h1>You are successfully Login</h1>
<h1>welcome User,
<bean:write name="LoginForm" property="username"/>   
</h1>
</body>
</html>

Twitter Delicious Facebook Digg Stumbleupon Favorites More