Friday, December 25, 2009

Struts

Struts is the open source MVC FrameWork.It is Flexible control layer based on standard technologies like java servlet,Java beans,Resourcebundle and XML.Structs privodes own controller component and integrates with other technologies to provide model and view.
For model structs integrate with standard data access like JDBC or EJB and other third party package like hibernate and ibatis. Or Other Object relation bridge.For View , Struts works well Jsp,JSTL or Other Presentation Layer System.

ActionServlet Class: It is the FrontEnd Controller of Struct Framework.It receive the requests from browser and make decision where to send the request based on struts-config.xml. Controller is responsible for handling all the requests

Action class: is Part of Model and wrapper around the business layer.
The purpose of action class is translate httprequest to business logic.
To use the action we need to subclass it and overwrite the execute method.

Action Form: represents the HTTP input data. They carry data over the one request to another.it maintance the state of an application.It is the Abstract class,which is subclassed for every input form model.the struts-config.xml file controls,which HTML Form request maps to which Action Form.

ActionMapping: means the action which is mapped to particular request.its configured in Struts-config.xml through action-tag.in which mention type of action form name action name and input formdetails.

ActionForward: means class which takes of forwarding the actions which are found through the action mapping class to their respective File.


1.Forward Action
2.Dispatch Action
3.include Action
4.LookUpDispatch Action
5.MappingDispatch Action
6.switch Action
7.LocaleDispatch Action

1.ForwardActionclass enables a user to forward request to the specified URL. ForwardAction is an utility classs that is used in cases where a user simply needs to forward the control to an another JSP page. Linking directly a JSP to an another, violates the MVC principles.

2.DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD. method also can have user-defined methods

3.IncludeAction is much like ForwardAction except that the resulting resource is included in the HTTP response instead of being forwarded to. It is rarely used. Its only significant use is to integrate legacy applications with Struts transparently

4.LookupDispatchAction: This type of aggregation is useful in situations where in you have multiple submit buttons in a single form. The class must extend LookupDispatchAction

5. MappingDispatchAction class is much like the DispatchAction class except that it uses a unique action corresponding to a new request , to dispatch the methods

6. SwitchAction class is used to support switching from module to module. Let's say you have an action that wants to forward to an action in another module.


Controller class ActionServlet is he request Dispatcher.
where as Action classes are request processer.



DispatchAction and LookupDispatchAction both are used to combine related operations into a single class, so that they can share common resources like helper methods without exposing them to other classes.

DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file. This will be problematic for internationalized applications since the values will be different for different locales. So, LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method.

RequestDispatcher class is mainly used to 'pass on' the current request to another program (servlet) and therefore allows 'chaining' of the programs. A RequestDispatcher primarily contains two methods include() and forward().include() method includes the response of another program while forward() method forwards the request of the current program to another one.

RequestDispatcher vs sendRedirect:

1) forward() is a server-side redirect. url on the browser doesn't change. This method is normally used for sending a request and response object to resources (servlets or JSP's) which are in the same ServletContext.
RequestDispatcher rd = request.getRequestDispatcher("/forms/search");
rd.forward(request, response);

2) sendRedirect() happens on the client-side i.e server sends a redirect url to a client status of http 301 and the url on the browser changes to the redirected value. RequestDispatcher in ServletContext can be used to dispatch the request to a different context.
Response.sendRedirect();


<span style="font-weight:bold;">ForwardAction Ex:</span>

<action
path="/success"
type="org.apache.struts.actions.ForwardAction"
parameter="/pages/Success.jsp"
input="/pages/ForwardAction.jsp"
scope="request"
validate="false">
</action>

<span style="font-weight:bold;">DispatchAction EX:</span>

<action path="/user" parameter="parameter"
type="net.viralpatel.struts.helloworld.action.UserManagementAction">
<forward name="success" path="/UserSuccess.jsp" />
<forward name="failure" path="/UserSuccess.jsp" />
</action>

<span style="font-weight:bold;">.IncludeAction</span>
<action path=”/legacyA”
parameter=”/xoom/LegacyServletA”
type=”org.apache.struts.actions.IncludeAction” />

<span style="font-weight:bold;">LookupDispatchAction EX:</span>

<html:submit property="submit"><bean:message key="button.create"/></html: submit >
<html:submit property="submit"><bean:message key="button.read"/></html: submit >
...
The example Action class will be as follows

public class CRUDLookUpDispatchAction extends LookupDispatchAction {

protected Map getKeyMethodMap() {
Map map = new HashMap();
map.put("button.create", "create");

return map;
}
public ActionForward create(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
return (mapping.findForward("success"));
}

SwitchAction Ex:

1. First, map a SwitchAction into the default module as shown here:
<action
path="/switch"
type="org.apache.struts.actions.SwitchAction"
>
</action>
2. Now, you can set up a forward in the action that edits the users as follows:
<action
path="/userSubmit"
attribute="userForm"
input="/form/userForm.jsp"
name="userForm"
scope="request"
type="action.UserAction">
<forward
name="success"
path="/switch.do?page=/listUsers.do&prefix=/admin"
/>
</action>

<span style="font-weight:bold;">MappingDispatchAction Ex:</span>
<action path="/MappingDispatchAction"
type="roseindia.net.MappingDispatch_Action"
parameter="edit"
input="/pages/MappingDispatchAction.jsp"
scope="request"
validate="false">
<forward name="edit" path="/pages/MappingDispatchActionEdit.jsp" />
</action>

Internationalization
Internationalization is a complex and involved subject. In brief, it refers to the automatic rendering of an application in the user's chosen language. It relates not only to the text itself, but also to numbers, date format, and currency values. Special symbols and alphabetical sorting in different languages bring interesting and unexpected problems with them.

Introduction to 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 to validate the form data on the client browser. Server sidevalidation of the form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

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>

<!-- Standard Action Servlet Configuration (with debugging) -->
<servlet>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationController.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>ApplicationResources</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>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>validate</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>


<!-- Standard 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>

</web-app>


struts-config.xml
----------------------------------------------------------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
Form bean Definitions

<form-beans>
<form-bean name="CustomerForm" type="mybank.example.CustomerForm">
<form-property name=”username” tpe=”java.lang.String”>
<form-property name=”password” tpe=”java.lang.String”>
</form-bean>
<form-bean name="LogonForm" type="mybank.example.LogonForm"/>
</form-beans>
Global Forward Definitions
<global-forwards>
<forward name="logon" path="/logon.jsp"/>
<forward name="logoff" path="/logoff.do"/>
</global-forwards>
Action Mappings
<action-mappings>
<action path=”/welcome” type=”org.apache.struts.actions.ForwordAction” parameter=”.mainLayout”/>

<action path="/submitDetailForm" type="mybank.example.CustomerAction" name="CustomerForm" scope="request"
validate="true" input="/CustomerDetailForm.jsp">
<forward name="success" path="/ThankYou.jsp" redirect=”true” />
<forward name="failure" path="/Failure.jsp" />
</action>

<action path=”/logoff” parameter=”/logoff.jsp” type=”org.apache.struts.action.ForwardAction” />
</action-mappings>
Controller Configuration
<controller processorClass="org.apache.struts.tiles.Tiles.RequestProcessor" />
Message Resource Definition
<message-resources parameter="mybank.ApplicationResources"/>
PlugIn Definition
<plugin className=”org.apache.struts.tiles.TilesPlugIn”>
<set-property name=”definations-config” value=”/WEB-INF/tiles-defs.xml”/>
<set-property name=”moduleWare” value=”truel”/>
</plugin>

<plugin className=”org.apache.struts.validator.ValidatorPlugIn”>
<set-property name=”pathnames” value=”/WEB-INF/validation.xml,/WEB-INF/validation-rules.xml”/>
</plugin>

<plugin className=”org.springframework.web.struts.ContextLoaderPlugIn”>
<set-property name=”contextConfigLocation” value=”/WEB-INF/applicationContext.xml”/>
</plugin>
</struts-config>

applicationContext.xml
-------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="myHibernateProperties" class="org.springframework.bean.factory.PropertyFactoryBean" destroy-method="close">
<property name="hibernateProperties"><value>classpath:Hibernate.properties</value></property>
</bean>

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property>(jdbc.oracle.driver.OracleDriver)
<property name="url"><value>jdbc:mysql://localhost:3306/techfaq</value></property>(jdbc:oracle:thin:@localhost1521:dbname)
<property name="username"><value>techfaq</value></property>
<property name="password"><value>techfaq</value></property>
</bean>

<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"><ref bean="myDataSource"/></property>
<property name="mappingResources">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<value><ref local=”myHibernateProperties”></value>
</property>
</bean>

<bean id=”myTransactionManager” class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name="sessionfactory"><ref bean="mySessionFactory"/></property>
</bean>

<bean id=”baseTransactionProxy” class=”org.springframework.transaction.interceptor.TransactionProxyFactoryBean”>
<property name=”transactionManager” ><ref local=”myTransactionManager”/></property>
<property name=”transactionAttributes” >
<props>
<prop key=”get*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”load*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”find*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
<prop key=”save*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”update*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”delete*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”clean*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
<prop key=”*”>PROPAGATION_REQUIRED,ISOLATION_DEFAULT,RollbackException </prop>
</props>
</property>
</bean>

<bean id="userdao” parent=”baseTransactionProxy”>
<property name="target">
<bean id=”targetUserDAO” class=”org.spb.UserHibernateDAO”>
<property name=”sessionFactory”> <ref local=”mySessionFactory”>
</property>
</bean>
<bean id="userservice" class="com.UserServiceImplementation" autowire=”autodetect”/>


<bean id="userservice" class="com.UserService">
<property name="userdao"><ref bean="userdao"/></property>
</bean>
</beans>

No comments:

Post a Comment