struts

43
Struts

Upload: vedicsoft

Post on 13-Nov-2014

921 views

Category:

Documents


3 download

DESCRIPTION

Struts

TRANSCRIPT

Page 1: Struts

Struts

Page 2: Struts

Agenda

• Introduction• ”C” in MVC• ”M” in MVC• ”V” in MVC• Workflow • Configuring Struts configuration file• Struts custom tags• Validator framework• File upload• Pros and Cons

Page 3: Struts

Introduction Struts is a framework to develop MVC model 2

applications Provides its own controller Separates presentation logic and business logic Open source http://struts.apache.org/ Approximately 300 java classes divided into 8 top level

packages Struts resides in the web tier Struts applications are hosted by a web container Makes heavy use of request and response objects Named in the architectural sense meaning nearly invisible

pieces holding up buildings Support different model implementations (Java bean,EJB

etc) Supports different view implementations (JSP,XML/XSL)

Page 4: Struts

Introduction

Struts packages

org.apache.struts.action

org.apache.struts.actions

org.apache.struts.config

org.apache.struts.taglib

org.apache.struts.upload

org.apache.struts.tiles

org.apache.struts.util

org.apache.struts.validator

Jar

struts.jar

Page 5: Struts

“C” in MVC

Controller component responsibilities

Receive request from client

Map request to specific business operation

Determine the view to display based on the result of

the business operation Controller is implemented by the ActionServlet,

RequestProcessor and Action classes ActionServlet

Extends HttpServlet

Forwards the request to RequestProcessor

This in turn forwards the request to helper class (which is a subclass of org.apache.struts.action.Action class)

Page 6: Struts

“C” in MVC

ActionServlet must be configured in web.xml

<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></servlet><servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern></servlet-mapping>

Config parameter should contain the path of the default struts config file.

Page 7: Struts

“C” in MVC

Container will load the ActionServlet either when starting the server or when the first request arrives for the servlet.

Init() method will be called before any request is processed by the servlet.

Performs compulsory initializations like initializing the message bundle, struts configuration data, data sources, plug-ins etc.

Users can extend the ActionServlet class. One instance of this servlet class receives and processes all requests Delegates the handling of the request to RequestProcessor object RequestProcessor selects and invokes an Action class to perform the

requested business operation Users can extend the RequestProcessor class.

Page 8: Struts

“C” in MVC Action class is the heart of the struts framework Bridge between a client request and a business

operation One action class for one business operation Most important method is the execute method which

will be called by the controller when a request is received from a client

Signature of the execute method:

public ActionForward execute(ActionMapping mapping, ActionForm form, javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws java.lang.Exception

Page 9: Struts

“C” in MVC

Single instance processes many requests, so care should be taken to ensure that they operate properly in multithreaded environment

Can create a base action class (which can contain common logic like checking session timeout etc) and let all other action classes extend the base action class.

EncorrAction extends Action OutgoingLogAction extends EncorrAction

IncomingLogAction extends EncorrAction

Page 10: Struts

“C” in MVC DispatchAction class Extends Action class Used to combine many similar actions into a single action class

(to combine add, modify and view actions) Dispatches to a public method whose signature should be

exactly same as the execute method For ex we can have 3 three methods in the same action class public ActionForward insert(ActionMapping mapping………… public ActionForward update(ActionMapping mapping………… public ActionForward delete(ActionMapping mapping………… http://localhost:8080/myapp/saveSubscription.do?

method=update will call the update method.

EncorrAction extends DispatchAction OutgoingLogAction extends EncorrAction

IncomingLogAction extends EncorrAction

Page 11: Struts

“C” in MVC To summarize controller consists of

ActionServlet

RequestProcessor

Action/DispatchAction

Classes in action package

ActionServlet

RequestProcessor

Action

ActionForm

ActionForward

ActionMapping

Page 12: Struts

“M” in MVC Model consists of data and the functions that operate

on data Java bean that we use to store data is a model

component EJB can also be used as a model component

Page 13: Struts

“V” in MVC View can be a HTML JSP Struts ActionForm

Struts ActionForm Struts framework automatically collects input from

request, passes this data to an Action using a form bean which can then be passed to the business layer.

An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its properties initialized from the corresponding request parameters before the corresponding Action.execute method is called.

Page 14: Struts

“V” in MVC Sample ActionForm bean public class UploadForm extends ActionForm { protected String myText; protected FormFile myFile;

public void setMyText(String text) {

myText = text; } public String getMyText() {

return myText; }

public void setMyFile(FormFile file) {

myFile = file; } public FormFile getMyFile() {

return myFile; }

}

Page 15: Struts

“V” in MVC Struts DynaActionForm

Specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean.

So to summarize view consists of

HTML

JSP or XML/XSL

ActionForm/ DynaActionForm

Page 16: Struts

WorkflowMVC

Page 17: Struts

WorkflowWorkflow

Page 18: Struts

WorkflowWorkflow

Page 19: Struts

Workflow1. The ActionServlet receives the request.

2. Based on the request URI, the ActionServlet retrieves the ActionMapping that defines the request.

3. The ActionServlet populates the ActionForm object from the HTTP request. If the ActionMapping specifies that validation is required, the ActionServlet calls the validate() method on the ActionForm object.

4. The ActionServlet invokes the execute() method of the Action object, providing the ActionForm object as a parameter. The method returns an ActionForward object specifying where to forward the request.

5. The ActionServlet forwards the request to the resource specified in the ActionForward object. This is typically a JSP (the view), but it can send the request to another Action.

6. It sends the response back to the browser.

Page 20: Struts

Configuring Struts Configuration File ApplicationResources.properties

Element/Value pairs (multi-lingual support) Easy to change properties referenced in many places in the page Can have multiple files for different languages

Sample

errors.required={0} is required.errors.minlength={0} can not be less than {1} characters.errors.maxlength={0} can not be greater than {1} characters.exception.outgoinglogcreate.action.error = Internal Server Error in Create

Outgoing Logexception.outgoinglogupdate.action.error = Internal Server Error in Update

Outgoing Log

Page 21: Struts

Configuring Struts Configuration FileStruts config file

Core of struts Ties all the components of the struts application together 2 main parts are form bean and action mappings

Sections of struts-config.xml Data source Form bean (Form property) Exception Forward Action Controller Message Resources PlugIn

Each class in org.apache.struts.config package holds information from the specific section of the configuration file

Classes in config packageApplicationConfig Holds configuration information that describes an entire struts applicationDataSourceConfig Holds information about data source.

Page 22: Struts

Configuring Struts Configuration FileFormBeanConfig To configure multiple DynaActionForm classes that are

used by the viewsFormPropertyConfig To configure form properties<form-beans>

<form-bean name=“newOutgoingLog“ type="org.apache.struts.action.DynaActionForm"> <form-property name=“ccTo" type="java.lang.String" /> <form-property name=“subject" type="java.lang.Integer" initial=”NewsLetter”/></form-bean>

<form-bean name=“newIncomingLog“ type="org.apache.struts.action.DynaActionForm"> <form-property name=“dueDate" type="java.lang.String" /> <form-property name=“assignee" type="java.lang.Integer" initial=”NewsLetter”/></form-bean>

</form-beans>

Page 23: Struts

Configuring Struts Configuration FileIn execute method of Action class,

import org.apache.commons.beanutils.BeanUtils;

DynaActionForm dynaActionForm = (DynaActionForm)form;

OutgoingLogBean outgoingLogBean = new OutgoingLogBean();

BeanUtils.copyProperties(outgoingLogBean,dynaActionForm);

Page 24: Struts

Configuring Struts Configuration File ExceptionConfig

Describes a mapping between a java exception and a handler which is responsible for dealing with the exception

2 types

1.Global exception 2.Action specific exception

Global Exception <global-exceptions>

<exception key="exception.nullexception.error" type=“java.lang.NullPointerException" path="jsp/ECError.jsp"/>

</global-exceptions>

When NullPointerException exception occurs, forward the request to ECError.jsp and build an error message using the key exception.nullexception.error (from resource bundle)

Page 25: Struts

Configuring Struts Configuration FileAction specific exception

<action path="/outgoing" name="newOutgoingLog" type="org.worldbank.encorr.ecAction.OutgoingLogAction" scope="request" parameter="method">

<exception key="exception.outgoinglogcreate.action.error" type="org.worldbank.encorr.exception.OutgoingTicketCreationException" path="jsp/ECError.jsp"/>

</action>

When OutgoingLogAction exception occurs, forward the request to ECError.jsp and build an error message using the key exception.outgoinglogcreate.action.error (from resource bundle)

Assume in resource bundle, exception.outgoinglogcreate.action.error = Internal Server Error in Create

Outgoing Log So the error message would be Internal Server Error in Create Outgoing Log

when OutgoingTicketCreationException is thrown.

Page 26: Struts

Configuring Struts Configuration File

ForwardConfig

Every action finishes by forwarding or redirecting to a view. Each view would be given a logical name and the framework will forward to the view by referring the logical name.

2 types 1.Global forward 2.Action specific forward

Global forward <global-forwards>

<forward name="success" path="/jsp/Success.jsp"></forward> </global-forwards>

In action class ActionForward forward = null; forward = mapping.findForward(“success”); return forward;

Page 27: Struts

Configuring Struts Configuration File ActionConfig

Describes a mapping between a specific request URI and a corresponding Action class.

<action path="/outgoing" name="newOutgoingLog" type="org.worldbank.encorr.ecAction.OutgoingLogAction" scope="request" parameter="callMethod">

<exception ……………../><exception ……………../><forward ………………/><forward ………………/>

</action>

Attributes path – URI path name – Name of the form bean associated with this Action type – Name of the java class that extends Action/DispatchAction class scope – specifies the scope in which the form bean is placed (request or session) parameter – Name of the request parameter which holds the name of the method to be executed. forward – Name of the servlet/JSP which will be forwarded to instead of calling the Action class include – Name of the servlet/JSP which will be included with the response instead of calling the Action class (type, forward and include are mutually exclusive and exactly one should be specified validate – Boolean value indicating if validate() method should be called before calling Action class method

Page 28: Struts

Configuring Struts Configuration File

ControllerConfig

To declaratively assign the processor class (RequestProcessor) and modify its functionality

Page 29: Struts

Configuring Struts Configuration File

MessageResourcesConfig

Specifies message resource bundle that contains localized messages for an

application

<message-resources parameter="org.worldbank.encorr.resources.ApplicationResources”/>

Page 30: Struts

Configuring Struts Configuration File PlugInConfig

To discover resources dynamically at startup.

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">

<set-property property="pathnames"

value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />

</plug-in>

Page 31: Struts

Struts custom tags Package

org.apache.struts.taglib

TLDsstruts-html.tldstruts-bean.tld

struts-logic.tldstruts-nested.tldstruts-template.tldstruts-tiles.tld

The "struts-html" tag library contains JSP custom tags useful in creating dynamic HTML user interfaces, including input forms.

In JSP,<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:javascript>

Page 32: Struts

Struts custom tags<html:javascript>

Custom tag that generates JavaScript for client side validation based on the validation rules loaded by the ValidatorPlugIn

<html:javascript formName="newOutgoingLog"/>

<html:form>

Custom tag that represents an input form, associated with a bean whose properties correspond to the various fields of the form.

<html:form action="outgoing.do" method="post" onsubmit="return onClickSave(this);">

<html:hidden>

Custom tag for input fields of type "hidden".

<html:hidden property="ticketStatus" value="C"/>

<html:select>

Custom tag that represents an HTML select element, associated with a bean property specified by our attributes

<html:options>Tag for creating multiple <select> options from a collection.

Page 33: Struts

Struts custom tagspublic class ListData {

public String optLabel = null;public String optValue = null;

public String getOptLabel() {return optLabel;

}public void setOptLabel(String optLabel) {

this.optLabel = optLabel;}public String getOptValue() {

return optValue;}public void setOptValue(String optValue) {

this.optValue = optValue;}

}

Page 34: Struts

Struts custom tags

ArrayList al = new ArrayList();

ListData ld = new ListData();ld.setOptValue(“100”);ld.setOptLabel(“English”);al.add(ld);

ld = new ListData();ld.setOptValue(“101”);ld.setOptLabel(“Tamil”);al.add(ld);

ld = new ListData();ld.setOptValue(“102”);ld.setOptLabel(“Hindi”);al.add(ld);

request.setAttribute("languageList",al);

<html:select property="language"><html:options collection="languageList" property=“optValue" labelProperty=“optLabel"/>

</html:select>

Page 35: Struts

Struts custom tags

<html:errors>Custom tag that renders error messages if an appropriate request attribute

has been created. <html:errors/>

<html:file>Custom tag for input fields of type "file".

Page 36: Struts

Validator framework

PurposeFor performing data validations on form data. If any validation fails the application redisplays the HTML form so that the invalid data

can be correctedPluggable system of validation routines that can be applied to form beans.

2 XML configuration files

1.validator-rules.xmlDeclares the validation routines with a logical name for each routine.

2.validation.xmlDefines which validation routine should be applied to which form bean

property.It uses logical names of form beans from the struts-config.xml file along

with the logical names of validation routines from validator-rules.xml

Page 37: Struts

Validator framework

Struts-config.xml

<form-bean name="newOutgoingLog" type="org.apache.struts.action.DynaActionForm">

<form-property name="subject" type="java.lang.String"></form-property>

</form-bean>

<action path="/outgoing" name="newOutgoingLog"

type="org.worldbank.encorr.ecAction.OutgoingLogAction"

scope="request" parameter="method">

</action>

Page 38: Struts

Validator framework

Validator-rules.xml

<validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object, org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest" msg="errors.required"> <javascript><![CDATA[ function validateRequired(form) { ………………………………………………………. }]]> </javascript> </validator>

Page 39: Struts

Validator frameworkValidation.xml

<form name="newOutgoingLog">

<field property="subject" depends="required">

<arg0 key=“Subject field" resource="false"/>

</field>

</form>

In resource bundle,

errors.required={0} cannot be left blank.

Page 40: Struts

File uploadIn jsp, <html:file name="IncomingLogBean" property="fileAttachment1"/>

In struts-config.xml,

<form-bean name="newOutgoingLog" type="org.apache.struts.action.DynaActionForm"> <form-property name="fileAttachment1" type="org.apache.struts.upload.FormFile" /></form-bean>

In OutgoingLogBean,

private FormFile fileAttachment1;public FormFile getFileAttachment1() {

return fileAttachment1;}public void setFileAttachment1(FormFile fileAttachment1) {

this.fileAttachment1 = fileAttachment1;}

Page 41: Struts

File uploadIn Action class,

DynaActionForm dynaActionForm = (DynaActionForm)form;

OutgoingLogBean outBean = new OutgoingLogBean();

BeanUtils.copyProperties(outBean,dynaActionForm);

FormFile fileAttachment = outBean.getFileAttachment1();

String fileName = fileAttachment.getFileName() ;

byte b[] = fileAttachment.getFileData();

Page 42: Struts

Pros and ConsPros

Open source Reduces the development time No hard codings as struts values are represented in XML or properties file HTML custom tags (Minimize Java code in JSP) Form field validation

Cons

Bigger learning curve (understanding of servlets,JSPs is required) Less transparent (lot more goes behind the scenes) Rigid approach (suggests only MVC approach.Cant use other approaches)

Page 43: Struts

Thank You