P. 1
Struts 1

Struts 1

4.0

|Views: 746|Likes:
Published by api-3745771

More info:

Published by: api-3745771 on Oct 17, 2008
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

03/18/2014

pdf

text

original

What is Struts? Struts is a java framework based on Model 2 architecture of JSP or popularly called ModelView-Controller architecture.

It provides a controller for this architecture. Explain Struts navigation flow? Struts Navigation flow. 1) A request is made from previously displayed view. 2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic. 3)The Action Class performs its logic on the Model Components associated with the Application. 4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation. 5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action. What is the difference between Struts 1.0 and Struts 1.1? The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml 4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins 7.Multiple Application Modules 8.Nested Tags 9.The Struts Validator 10.Change to the ORO package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of the GenericDataSource.

What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file? 1. tiles-def.xml tiles-def.xml is used as a configuration file for an appliction during tiles development You can define the layout / header / footer / body content for your View. Eg: <tiles-definitions> <definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp"> <put name="title" value="Title of the page" /> <put name="header" value="/include/thbiheader.jsp" /> <put name="footer" value="/include/thbifooter.jsp" /> <put name="content" type="string"> Content goes here </put> </definition> </tiles-definitions> <tiles-definitions> <definition name="userlogin" extends="siteLayoutDef"> <put name="content" value="/dir/login.jsp" /> </definition> </tiles-definitions> 2. validation.xml The validation.xml file is used to declare sets of validations that should be applied to Form Beans. Each Form Bean you want to validate has its own definition in this file Inside that definition, you specify the validations you want to apply to the Form Bean's fields. Eg: <form-validation> <formset> <form name="logonForm"> <field property="username" depends="required"> <arg0 key=" prompt.username"/> </field> <field property="password" depends="required"> <arg0 key="prompt.password"/> </field>

</form> </formset> </form-validation> 3. Resourcebundle.properties Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails. Eg: In ApplicationResources.properties errors.registrationForm.name={0} Is an invalid name. In the registrationForm.jsp <html:messages id="messages" property="name"> <font color="red"> <bean:write name="messages" /> </html:messages> Output(in red color) : abc Is an invalid name ================= 1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is fixed" center might be dynamically chaged. It is used for the easy design of the web sites. Reusability 2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file. 3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms. ============================ tiles-def.xml - is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need

tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor. resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC. validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.

What we will define in Struts-config.xml file. And explain their purpose? In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins Example : <!– Date Sources –> <data-sources> <data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin"> </<data-sources> <!– Form Beans –> <form-beans> <form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm"> </form-bean> <!– Global Exceptions –> <global-exceptions> <exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/> </global-exceptions> <!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–> <global-forwards> <forward name="logoff" path="/logoff"/> <forward name="logon" path="/logon.jsp"/> </global-forwards>

<!– Actionn Mappings –> <action-mappings> <action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm"> <forward name="success" path="/logon.jsp"> </forward> </action> </action-mappings> <!– Message Resources –> <message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/> <!– Plug-ins –> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEBINF/validation.xml"/> </plug-in> =============================== Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc. The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions. The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action. The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file. <global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page. The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method. <action-mappings/>: The action mapping mainly defines the mapping between the logical

Action name and the physical action class. Now lets have an understanding about its attributes. ツキ The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request. ツキ The type attribute specifies the absolute path of the fully qualified class name of the Action class. ツキ The attribute name must be the same as that of the form bean name for which you want to associate the action. ツキ The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session. ツキ The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action. ツキ The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute. <controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor. =============================== In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any. Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ? So, Controller servlet, needs this file to proceede/ run the application. What is DispatchAction? 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 [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc. This class apart from having thread-safe execute method also can have user-defined methods. In struts-config.xml files following changes are required for Dispatch action to work: <action-mappings> <action path="/login" type ="com…..LoginAction" name ="loginForm" parameter ="task"

scope = "request" validate = "false" input = "/index.jsp"> <forward name="success" path="/jsp/common/index.jsp"/> <forward name="loginagain" path="/index.jsp"/> </action> </action-mappings> If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url: http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version. How to call ejb from Struts? We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object. What is the difference between ActionErrors and ActionMessages? There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message. The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope. What are the various Struts tag libraries? The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) : * Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their

properties. Developers can also define new beans and set properties * HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons * Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management * Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation * Nested tag library [ struts-nested.tld ] : allows the use of nested beans. The libraries are designed to: * Facilitate the separation of presentation and business logic. * Dynamically generate Web pages. * Implement the flow of control to and from the ActionServlet. How you will handle errors and exceptions using Struts? Struts exception handling can be done by two ways: 1. Declarative (using struts features via struts-config.xml) <global-exceptions> <exception type="hansen.playground.MyException2" key ="errors.exception2" path="/error.jsp"/> </global-exceptions> This makes coding in the Action class very simple Since the execute method declares throws Exception we don't need a try-catch block. Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object. 2. Programmatic (using the usual try-catch exception handling in Action Class) =============== We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages. ================= Struts handles errors by providing the ActionErrors class which is extended from org.apache.struts.action… To install your customized exception handler, the first step is to create a class that extends org.apache.struts.action.ExceptionHandler. There are two methods that you can override, execute() and storeException(). For handling exceptions you have to mention in <global-exceptions> tag of struts-config.xml which accepts attributes like exception type,key and path.

How you will save the data across different pages for a particular client request using Struts? One simple and general way is by using session Object. In specific, we can pass this by using request Object as well. ====================================== Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request. request.getSession() session.setAttribute() What is Action Class? What are the methods in Action class? An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server. Some of the impotant methods of Action class are, execute() generateToken() resetToken() getServlet() Explain about token feature in Struts? Use the Action Token methods to prevent duplicate submits: There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised. saveToken(request) on the return trip, isTokenValid(request) resetToken(request)

What is the difference between ActionForm and DynaActionForm # The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment. # ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file. # ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ). # DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided. # Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)

STRUTS
Struts is an application development framework that is designed for and used with the popular J2EE (Java 2, Enterprise Edition) platform. It cuts time out of the development process and makes developers more productive by providing them a series of tools and components to build applications with. It is non-proprietary and works with virtually any J2EE-compliant application server. The Model-View-Controller Architecture “Model-View-Controller” is a way to build applications that promotes complete separation between business logic and presentation. It is not specific to web applications, or Java, or J2EE ,but it can be applied to building J2EE web applications. Model: Model is responsible for providing the data from the database and saving the data into the data store. All the business logic are implemented in the Model. Data entered by the user through View are check in the model before saving into the database. Data access, Data validation and the data saving logic are part of Model. View: View represents the user view of the application and is responsible for taking the input from the user, dispatching the request to the controller and then receiving response from the controller and displaying the result to the user. HTML, JSPs, Custom Tag Libraries and Resources files are the part of view component.

Controller: Controller is intermediary between Model and View. Controller is responsible for receiving the request from client. Once request is received from client it executes the appropriate business logic from the Model and then produce the output to the user using the View component. ActionServlet, Action, ActionForm and struts-config.xml are the part of Controller. Struts Components 1.Controller This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It’s provided by the framework. 2.Structs-cofig.xml File This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application. 3.Action Classes It’s the developer’s responsibility to create these classes. They act as bridges between userinvoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They’re part of the Controller layer, not the Model layer. 4.View Resources View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags. 5.ActionForms These greatly simplify user form validation by capturing user data from the HTTP request. They act as a “firewall” between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed. ************************************************************************************************* FAQS What is Struts? Struts is a java framework based on Model 2 architecture of JSP or popularly called ModelView-Controller architecture.It provides a controller for this architecture. Explain Struts navigation flow? Struts Navigation flow. 1) A request is made from previously displayed view. 2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the

Action class that has to perform the requested business logic. 3)The Action Class performs its logic on the Model Components associated with the Application. 4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation. 5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action. What is the difference between Struts 1.0 and Struts 1.1? The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml 4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins 7.Multiple Application Modules 8.Nested Tags 9.The Struts Validator 10.Change to the ORO package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of the GenericDataSource. What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file? 1. tiles-def.xml tiles-def.xml is used as a configuration file for an appliction during tiles development You can define the layout / header / footer / body content for your View. Eg: <tiles-definitions> <definition name=”siteLayoutDef” path=”/layout/thbiSiteLayout.jsp”> <put name=”title” value=”Title of the page” /> <put name=”header” value=”/include/thbiheader.jsp” /> <put name=”footer” value=”/include/thbifooter.jsp” /> <put name=”content” type=”string”> Content goes here </put>

</definition> </tiles-definitions> <tiles-definitions> <definition name=”userlogin” extends=”siteLayoutDef”> <put name=”content” value=”/dir/login.jsp” /> </definition> </tiles-definitions> 2. validation.xml The validation.xml file is used to declare sets of validations that should be applied to Form Beans. Each Form Bean you want to validate has its own definition in this file Inside that definition, you specify the validations you want to apply to the Form Bean’s fields. Eg: <form-validation> <formset> <form name=”logonForm”> <field property=”username” depends=”required”> <arg0 key=” prompt.username”/> </field> <field property=”password” depends=”required”> <arg0 key=”prompt.password”/> </field> </form> </formset> </form-validation> 3. Resourcebundle.properties Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails. Eg: In ApplicationResources.properties errors.registrationForm.name={0} Is an invalid name. In the registrationForm.jsp <html:messages id=”messages” property=”name”> <font color=”red”>

<bean:write name=”messages” /> </html:messages> Output(in red color) : abc Is an invalid name ================= 1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage “top or bottom or left is fixed” center might be dynamically chaged. It is used for the easy design of the web sites. Reusability 2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file. 3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms. ============================ tiles-def.xml - is required if your application incorporates the tiles framework in the “View” part of MVC. Generally we used to have a traditional JSP’s (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp’s in struts like architectures, and we can define the jsp’s which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor. resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC. validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.

What we will define in Struts-config.xml file. And explain their purpose? In struts-config.xml we define Data Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins

Example : <!– Data Sources –> <data-sources> <data-source autoCommit=”false” description=”First Database Config” driverClass=” org.gjt.mm.mysql.Driver” maxCount=”4" minCount=”2" password=”admin” url=”jdbc: mysql://localhost/ARTICLEDB” user=”admin”> </<data-sources> <!– Form Beans –> <form-beans> <form-bean name=”registrationForm” type=”com.aaa.merchant.wsp.ActionForms.RegistrationForm”> </form-bean> <!– Global Exceptions –> <global-exceptions> <exception key=”some.key” type=”java.io.IOException” handler=”com.yourcorp.ExceptionHandler”/> </global-exceptions> <!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can’t find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–> <global-forwards> <forward name=”logoff” path=”/logoff”/> <forward name=”logon” path=”/logon.jsp”/> </global-forwards> <!– Actionn Mappings –> <action-mappings> <action path=”/validateRegistration” type=”com.dd.merchant.wsp.Actions.ValidateRegistration” validate=”true” input=”" name=”registrationForm”> <forward name=”success” path=”/logon.jsp”> </forward> </action> </action-mappings> <!– Message Resources –> <message-resources parameter=”wsppaymentsweb.resources.ApplicationResources”/> <!– Plug-ins –> <plug-in className=”org.apache.struts.validator.ValidatorPlugIn”> <set-property property=”pathnames” value=”/WEB-INF/validator-rules.xml,/WEBINF/validation.xml”/>

</plug-in> =============================== Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc. The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions. The <form-bean/> is configured using only two attributes, name and type and doesn’t contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action. The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file. <global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page. The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method. <action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes. ツキ The attribute path must be compulsorily defined and it should start with a ‘/’ character. It specifies the context relative path of the submitted request. ツキ The type attribute specifies the absolute path of the fully qualified class name of the Action class. ツキ The attribute name must be the same as that of the form bean name for which you want to associate the action. ツキ The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session. ツキ The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.

ツキ The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute. <controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor. =============================== In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any. Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ? So, Controller servlet, needs this file to proceede/ run the application. What is DispatchAction? 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 [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc. This class apart from having thread-safe execute method also can have user-defined methods. In struts-config.xml files following changes are required for Dispatch action to work: <action-mappings> <action path=”/login” type =”com…..LoginAction” name =”loginForm” parameter =”task” scope = “request” validate = “false” input = “/index.jsp”> <forward name=”success” path=”/jsp/common/index.jsp”/> <forward name=”loginagain” path=”/index.jsp”/> </action> </action-mappings> If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url: http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file’s action-mapping tag described above. The parameter property of <action> tag have the

task as it’s value pointing to task variable in the request having it’s value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version. How to call ejb from Struts? We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object. What is the difference between ActionErrors and ActionMessages? There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message. The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope. What are the various Struts tag libraries? The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) : * Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties * HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons * Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management * Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation * Nested tag library [ struts-nested.tld ] : allows the use of nested beans. The libraries are designed to: * Facilitate the separation of presentation and business logic. * Dynamically generate Web pages. * Implement the flow of control to and from the ActionServlet. How you will handle errors and exceptions using Struts?

Struts exception handling can be done by two ways: 1. Declarative (using struts features via struts-config.xml) <global-exceptions> <exception type=”hansen.playground.MyException2" key =”errors.exception2" path=”/error.jsp”/> </global-exceptions> This makes coding in the Action class very simple Since the execute method declares throws Exception we don’t need a try-catch block. Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object. 2. Programmatic (using the usual try-catch exception handling in Action Class) =============== We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages. ================= Struts handles errors by providing the ActionErrors class which is extended from org.apache.struts.action… To install your customized exception handler, the first step is to create a class that extends org.apache.struts.action.ExceptionHandler. There are two methods that you can override, execute() and storeException(). For handling exceptions you have to mention in <global-exceptions> tag of struts-config.xml which accepts attributes like exception type,key and path. How you will save the data across different pages for a particular client request using Struts? One simple and general way is by using session Object. In specific, we can pass this by using request Object as well. ====================================== Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request. request.getSession() session.setAttribute() What is Action Class? What are the methods in Action class?

An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server. Some of the impotant methods of Action class are, execute() generateToken() resetToken() getServlet() Explain about token feature in Struts? Use the Action Token methods to prevent duplicate submits: There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised. saveToken(request) on the return trip, isTokenValid(request) resetToken(request) What is the difference between ActionForm and DynaActionForm # The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger. # The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment. # ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file. # ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ). # DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided. # Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)

Project Life cycle

Misc
How to estimate project deadlines Before jumping into calculating or estimating a Project Timeline, I will go through the steps of how a software should be executed, so that whatever is estimated, actually works out that way. In the present day scenario where Time-to-Market issues achieve greater precedence over other issues, which we have learnt over the years, the developers’ productivity and quality of the software go out of the window. Has anyone thought why more and more open-source projects are gaining such popularity compared to their proprietary counterparts? The simple reason is the desire to build robust and good quality software where revenue earned is not the major criteria. Open-source developers have a different mindset, they code without selfishness, however that’s a different story. Coming back to the topic, the software life cycle consists of: 1. Analysis 2. Design 3. Construction 4. Deployment 5. Maintenance Each of the phases is tightly coupled with each other and a slippage in any of the phases will always carry down to the following phases. This brings us to the first phase, i.e. Analysis. Phase 1 – Analysis This is where the whole story begins. Analysis is the process of understanding the customer’s requirement and mapping it to the use cases. The most essential requirement of this phase is effective communication, however this fact is normally ignored. It must be understood that not all people are good at everything. Allocating the brightest brain in the organization for the Requirement Analysis may not be the best idea. By communicate effectively I mean a person who can give a patient listening rather than showing his oratory skills and of course one who is experienced in doing such kind of a job. Phase 2 – Design Once the foundation is laid with good use cases, it’s not that difficult a task to design the system. However one must keep in mind to use the best tools available for creating the software model. It is wise not to architect something new and venture into unseen territory to prove one’s designing skills, rather than use accepted models and architecture, which have matured over the years. Putting one’s designing prowess to test is best done with personal or open-source projects. Following the standards of designing will always result in a stable

model. Phase 3 – Construction Again as the skills of developers vary, the only way we can get good consistent code is by following high class coding and documentation standards. A good practice is to have an independent Code Reviewer, who is well versed with the coding and documentation standards, and who will do the review as the programs are being written so that the developers will not run a mock with their code with the attitude that ‘It will be done later’. This actually never happens. Once a code is written it always stays that way. The other important implementation during this phase is Unit testing and System testing. It sounds synonymous but there is a difference between the two, Unit testing is testing the performance of the methods of a class whereas System testing is the performance of a class when accessed from another class. This is important at this stage, as a bug is less expensive when found at an early stage as compared to when found during Functional testing. By implementing these simple measures, the Quality of software will definitely be enhanced. Phase 4 – Deployment One of the most critical steps in the software lifecycle is the deployment process. This is often a customer's first experience with a product and a bad experience can have lasting effects. Successful deployment depends on good System design and architecture of the project, which brings us back to the design phase. It is during the design phase itself deployment considerations should be kept in mind so that there are no hiccups during deployment. Phase 5 – Maintenance This phase will be a breeze if the Analysis, Design, Construction and Deployment have gone off smoothly. The reason is that the issues to deal with, during this phase, will be considerably reduced. There are many software processes formulated over the years, which deal with building robust and stable software of which the Rational Unified Process (RUP) and the Agile Unified Process (AUP) are widely used. Extreme Programming is also gaining popularity these days. No matter which process is being used by the organization, it has to be followed sincerely without making any exceptions. Calculating the Project Time The reason why I had elaborated on the phases of the software development cycle was to stress upon the fact that whichever method you use for estimating the timeline for a project, the project will be on schedule if and only if the aforesaid are implemented with sincerity. Making good time estimations requires a combination of qualities, which are experience, intuition and good technical skills. The method I am illustrating is the one by Derek C Ashmore, from his book titled the “The J2EE Architect’s Handbook”, which states that the approximate time for a project can be calculated by: a. The total number of screens multiplied by 2 man-weeks each

b. The total number of External application interfaces multiplied by 4 man-weeks each c. The total number of Database tables multiplied by 2 man-weeks each d. The total number of Tables or files updated multiplied by 2 man-weeks each This will give the base estimate for a single developer. Multiply the base estimate by 2.5 to include analysis and testing activities for each usecase, lets call this figure as the total estimate for a single developer. Now for each developer added to the project multiply the total estimate with 1.20 (As each developer added increases Communication and Management time, which is also time consumed for the project). At times when implementing the above strategy, some time estimations for certain modules of the project may seem a bit too inflated. In these circumstances adjust the assumptions made in a, b, c, d for those specific modules. Hope these inputs will be helpful to those interested.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->