DAO
D.B
Browser
WEB.XML
Struts-Config.xml
*.do
Action Servlet
parameter="/path/to/processing/servlet"/> ( forward to specific URL)
3.DispatchAction ( extends BaseAction configure in struts-config.xml <action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction"
name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/> public ActionForward delete(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
The standard Struts development model requires a view, an ActionForm for that view and an Action class, for every ActionForm.Your program should extend the DispatchAction class and provide implementation for each of the required methods.
The values for the method parameter, passed by your view should bear the same name as that of the respective method.
Create an action handler class which subclasses DispatchAction .
In that handler class, create the required methods to handle each of the actions.
Include an action mapping for this action handler using the parameter attribute in the struts-config.xml file. package com.abc.dispatchaction; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.actions.DispatchAction; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping;
public class UserDispatchAction extends DispatchAction { public ActionForward save(ActionMapping mapping,
ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException { String user = null;
if ( form != null ) {
UserForm userForm = (UserForm)form; user = userForm.getUser();
}
System.err.println("Saving user: " + user); // Forward to the appropriate View
return (mapping.findForward("success")); }
public ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response)
String user = null; if ( form != null ) {
UserForm userForm = (UserForm)form; user = userForm.getUser();
}
System.err.println("Removing user: " + user); // Forward to the appropriate View
return (mapping.findForward("success")); }
}
In DispatchAction, the Struts framework depended on the parameter values having the same name as their associated actions.
But LookupDispatchAction implements a key-value relationship that does away with the naming requirement of the DispatchAction.
Struts uses the key-value map to look up the corresponding method. And it also uses a resource bundle for displaying label data and messages
4. DownloadAction ( protected abstract HYPERLINK "http://struts.apache.org/1.x/strutsextras/ apidocs/org/apache/struts/actions/DownloadAction.StreamInfo.html" \o "interface in
org.apache.struts.actions" DownloadAction.StreamInfo Methods --> getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception
protected int getBufferSize()--> Returns the size of the buffer to be used in transferring the data to the servlet output stream. This method may be overridden by an extending class in order to customize the buffer size.
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception public int copy(InputStream input, OutputStream output)throws IOException --> Copy bytes from an InputStream to an OutputStream.
5. public class IncludeAction extends BaseAction --> An Action that includes the contextrelative URI specified by the parameter property of our associated ActionMapping. This can be used to integrate Struts with other business logic components that are implemented as
servlets (or JSP pages), but still take advantage of the Struts controller servlet's functionality (such as processing of form beans).
<action path= "/saveSubscription" type= "org.apache.struts.actions.IncludeAction" name="subscriptionForm" scope= "request" input= "/subscription.jsp"
parameter="/path/to/processing/servlet"> --> execute() method
6. public final class LocaleAction extends BaseAction --> Implementation of Action that changes the user's Locale and forwards to a page, based on request level parameters that are set (language, country, & page).
--> execute()
-->convenientmechanismforsettinguser‘slocale. --> create action mapping entry
7. public class SwitchAction extends BaseAction --> A standard Action that switches to a new module and then forwards control to a URI (specified in a number of possible ways) within the new module.
--> execute() method
--> switching between modules in modularized application --> similar to ForwardAction.
8. public class EventDispatchAction extends DispatchAction --> An Action that dispatches to one of the public methods that are named in the parameter attribute of the corresponding
ActionMapping and matches a submission parameter. This is useful for developers who prefer to use many submit buttons, images, or submit links on a single form and whose related actions exist in a single Action class.
<action path= "/saveSubscription" type= "org.example.SubscriptionAction" name= "subscriptionForm"
scope="request"
input="/subscription.jsp"
parameter="save,back,recalc=recalculate,default= save"/>
protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception protected String getMethodName(ActionMapping mapping, ActionForm form,
HttpServletRequest request,HttpServletResponse response, String parameter) throws Exception
public abstract class LookupDispatchAction extends DispatchAction --> An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an
HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. To configure the use of this
action in your struts-config.xml file, create an entry like this:
<action path= "/test" type= "org.example.MyAction" name= "MyForm" scope="request" input="/test.jsp" parameter="method"/>
protected abstract Map getKeyMethodMap()
protected String getLookupMapName(HttpServletRequest request, String keyName, ActionMapping mapping) throws ServletException
protected String getMethodName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response,
String parameter) throws java.lang.Exception --> extends DispatchAction
--> modularizing set of related functions into single action.
public class MappingDispatchAction extends DispatchAction --> An abstract Action that dispatches to a public method that is named by the parameter attribute of the corresponding
ActionMapping. This is useful for developers who prefer to combine many related actions into a single Action class.
<action path= "/saveSubscription" type= "org.example.SubscriptionAction" name= "subscriptionForm"
scope="request"
input="/subscription.jsp" parameter="method"/>
public ActionForward create(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
For Internationalization we need lookupDispatchAction that holds a method named getMethodKey() to find method based on method key.
A Dispatch Action calls the method based on Parameter Value where as in case of LookupDispatch Action does a lookup to determine the method based on lookup.
A typical Execution flow for a Project in Struts
1. Userentersthecontexturlinthebrowser‘saddressbar. http://localhost:8084/Struts2
2. The welcome-file associated with the application is displayed. index.jsp
3. User enters the data and clicks submit.
4. The<h:formaction=…>tagappends.dototheactionnameandsubmitstheformtothe server.
<html:form action="Lookup">
Lookup is the name of the action. It is changed to Lookup.do while being submitted to the server.Thisisdonebythe<h:form…/>element.
5. This .do extension is mapped to ActionServlet (Struts Controller Servlet) in the web.xml using the action-mapping element.
<servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet </servlet-class> ………. </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> ……….
6. Servlet Container now hands over control to ActionServlet along with the associated request, response objects.
7. ActionServlet reads the struts-config.xml and finds out the Action form bean and Action class for this url (action=Lookup)
<struts-config> <form-beans>
</form-beans> <action-mappings> <action
input="/index.jsp" name="LookupForm" path="/Lookup" scope="session" type="com.xyz.test.LookupAction"> <forward name="success" path="/quote.jsp"/> <forward name="failure" path="/index.jsp"/> </action>
</action-mappings> </struts-config>
8. It instantiates the Lookupform bean and populates it with request data.
9. If the bean instance is already present, it retrieves the instance and resets it with the request data.
10. In a similar manner, the controller instantiates or retrieves an instance of the Action Class, com.cts.test.LookupAction. 11. It then proceeds to create a mapping object, an instance of
ActionMapping , using the <action-mapping> details of the struts-config.xml.
12. As a next step, it invokes the execute() method of the Action class and passes the action form, action mapping , request and response objects as arguments.
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) ………..
13. The execute method, which is the model component, performs the application logic as specified in the code.
14. The execute method then returns an ActionForward object which specifies the next navigation target.
………
return (mapping.findForward(target));
15. The Struts Controller Servlet (ActionServlet), uses this ActionForward object and invokes the specified target view, which is determined from the <forward/>element of < action –mapping/>.
<action-mappings> <action
………
<forward name="success" path="/quote.jsp"/> <forward name="failure" path="/index.jsp"/> </action>
</action-mappings>
16. And, the cycle continues, if there happens to be more views in the application.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<!-- Action Servlet Configuration --> <servlet>
<servlet-name>action</servlet-name>
<init-param> <param-name>application</param-name> <param-value>test.struts.MessageResources</param-value> </init-param> <init-param> <param-name>mapping</param-name> <param-value>org.apache.struts.action.RequestActionMapping</param-value> </init-param> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>2</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet>
<!-- Action Servlet Mapping --> <servlet-mapping>
<servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri> <taglib-location>/WEB-INF/struts-html.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location> </taglib> <taglib> <taglib-uri>/WEB-INF/struts-template.tld</taglib-uri> <taglib-location>/WEB-INF/struts-template.tld</taglib-location> </taglib> </web-app> struts-config.xml Contents
data-sources—A set of data-source elements, describing parameters needed to instantiate JDBC 2.0 Standard Extension DataSource objects
<data-sources> <data-source autoCommit=‖false‖ description=‖SecondDatabaseConfig‖ driverClass=‖oracle.jdbc.driver.OracleDriver‖ key=‖REFDB‖ maxCount=‖4″ minCount=‖2″ password=‖admin‖ url=‖jdbc:oracle:thin:@localhost:1521/AUTHORDB‖ user=‖admin‖/> </data-sources>
form-beans—A set of form-bean elements that describe the form beans that this application uses <form-beans> <form-beanname=‖searchForm‖> type=‖com.abc.struts.SearchForm‖ </form-bean> </form-beans> DynaActionForm Bean
The struts application design requires you to develop a ActionForm class, for every jsp page you display for accepting user input.
Each of such ActionForm classes will have bean fields which represent the corresponding input fields. In a multi-navigation struts application, this could be major effort which is avoidable.
Its here that the DyanaActionForm comes to our rescue.
In fact, DynaActionForm is a java class provided by the struts framework.
It should be configured in the struts-config.xml of your struts application along with the property (data members) details.
Then the struts controller instantiates the actual form bean, using this configuration information. And hence, there is NO need to develop individual form bean classes (ActionForm), corresponding to each input jsp file.
<form-beans>
<form-bean name="dynamicLookupForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="symbol" type="java.lang.String" initial="MSFT" /> </form-bean>
</form-beans>
There need to be one <form-property../> entry for every input field in your view. In the Action Mapping, refer to the form using the name property in the usual way. <action-mappings> <action path="/DynaLookup" type="dya.DynaAction" name="dynamicLookupForm" input="/index.jsp">
<forward name="success" path="/quote.jsp"/> <forward name="failure" path="/index.jsp"/> </action>
DynaActionFom in Struts-Config.xml <form-bean name="dynamicLookupForm"
type="org.apache.struts.action.DynaActionForm">
<form-property name="symbol" type="java.lang.String" initial="MSFT" /> </form-bean>
</form-beans>
global-forwards—A set of forward elements describing general available forward URIs <global-forwards>
<forwardname=‖search‖path=‖/search.jsp‖/> </global-forwards>
ActionMapping
This will be a boolean property.
The execute() method of your action class will inspect this attribute and display messages only if true.
Implement the ActionForm class and Action class in the normal way as you do for any standard struts application.
Define a class that extends org.apache.struts.action.ActionMapping
Provide a default public constructor, which invokes the super class default constructor. Define the additional properties that you need to add as custom attributes.
Provide public setter and getter methods for these properties.
Include the className parameter in the action mapping elenment in the struts-config.xml file as follows: <action-mappings> <action className="camap.CustomMapping" path="/MapLookup" type="camap.LookupAction" name="lookupForm" scope=‖request‖ validate=‖true‖ input="/index.jsp">
<set-property property="displayResults" value="true"/> <forward name="success" path="/quote.jsp"/>
<forward name="failure" path="/index.jsp"/> </action>
</action-mappings>
Struts Internationalization Set Property files in JSP Application_Resources_en_US.properties ( for English,. US)
Application_Resources_it_IT.properties (for Italian, Italy)
Include an entry in struts-config.xml after action mapping as follows:
<message-resources parameter="com/myapp/struts/ApplicationResources"/> Sample Struts-Config.xml file
<?xml version= "1.0" encoding= "UTF-8"?> <!DOCTYPE struts-config
PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config> <form-beans>
<form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name= "password" type= "java.lang.String" />
<form-property name= "userName" type="java.lang.String" /> </form-bean> </form-beans> <global-exceptions> </global-exceptions> <global-forwards> </global-forwards> <action-mappings> <action attribute="loginForm" input="/login.jsp" name="loginForm" path= "/login" scope="request" type= "project.struts.actions.LoginAction" validate="true">
<forward name= "success" path="/index.jsp" redirect="true"/> <forward name= "failure" path= "/login.jsp" redirect="true"/> </action>
</action-mappings> <controller
processorClass= "org.apache.struts.tiles.TilesRequestProcessor" maxFileSize= "250M" bufferSize="4096" debug= "0" />
<message-resources parameter="struts" null="false" /> <plug-in className="org.apache.struts.tiles.TilesPlugin"> <set-property property="definitions-config"
value= "/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" /> </plug-in> <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames"
value= "/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" /> </plug-in>
</struts-config>
Reg Redirect in Struts
ActionRedirect redirect = new ActionRedirect(mapping.findForward("fwd.send")); redirect.addParameter("dispatch", "rev");
redirect.addParameter("commonInt", Integer.parseInt(request.getParameter("commonInt"))); return redirect;
<global-forwards>
<forward name="toModuleB" contextRelative="true" path="/moduleB/index.do" redirect="true"/>
By default its false ...
Struts-Config.xml – for email validation <form-beans>
<form-bean name="userForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="dob" type="java.lang.String" />
<form-property name="emailId" type="java.lang.String" /> </form-bean>
</form-beans> Validation.xml
<form name="userForm">
<field property="dob" depends="required,date"> <arg key="userForm.dob"/> <var> <var-name>datePattern</var-name> <var-value>MM-dd-yy</var-value> </var> </field>
<field property="emailId" depends="required,email"> <arg key="userForm.emailId"/>
</field> </form>
To ADD HIBERNATE IN STRUTS
<plug-in className="edu.arbor.util.plugin.HibernatePlugIn"> <set-property property="configFilePath" value="path-to-config-file" /> <set-property property="storeInServletContext" value="true-or-false" /> </plug-in>
<!—―path-to-config-file' is relative to the root of the class path. It MUST start with a '/'. The default is "/hibernate.cfg.xml" -->
Call Spring in Struts <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> </plug-in> <action-mappings> <action path="/widgetListAction" type="org.springframework.web.struts.DelegatingActionProxy" scope="request"> </action> </action-mappings> For tiles in web.xml <taglib>
<taglib-uri>/tags/struts-tiles</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location> </taglib>