40
1 Struts an MVC framework Prasad Chaturvedula

Struts PPT

Embed Size (px)

Citation preview

Page 1: Struts PPT

1

Struts an MVC framework

Prasad Chaturvedula

Page 2: Struts PPT

2

Introduction

Components of a struts app

Impact on development lifecycle

Best Practices

Page 3: Struts PPT

3

Struts Framework provides the Controller portion of the application

Receives requests from the client, decide what business logic function to perform, and delegate responsibility for producing the next phase of the user interface to an appropriate View component

Page 4: Struts PPT

4

Background

Components of a struts app The Action Servlet

The config file

ActionMapping

The Action Form

The Action Class

Action Errors and Validation framework

Page 5: Struts PPT

5

Data subsets

Action Servlet A normal servlet with some processing methods

thrown in to load config files and resource files

Reads config file and converts XML tagged information into copncrete Java objects using Digester

Delegates handling of a request to the Request Processor

Servlet Initialization parameters

configFile, configFactory, appResources

Page 6: Struts PPT

6

Road Ahead

<!-- Standard Action Servlet Configuration --><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>

Page 7: Struts PPT

7

Road Ahead

This servlet is responsible for handing all the request for the Struts Framework, user can map the specific pattern of request to the ActionServlet. <servlet-mapping> tag in the web.xml file specifies the url pattern to be handled by the servlet

The above mapping maps all the requests ending with .do to the ActionServlet. ActionServlet uses the configuration defined in struts-config.xml file to decide the destination of the request. Action Mapping Definitions is used to map any action

Page 8: Struts PPT

8

Why bother?

RequestProcessor Identify, from the incoming request URI, the substring

that will be used to select an action procedure.

Use this substring to map to the Java class name of the corresponding action class

If this is the first request for a particular <code>Action</code> class, instantiate an instance of that class and cache it for future use.

Only 1 instance of the Action class for all requests

Page 9: Struts PPT

9

Work Flow

RequestProcessor contd Optionally populate the properties of an ActionForm bean

associated with this mapping.

Call the execute method of this Action class, passing on a reference to the mapping that was used, the relevant form-bean (if any), and the request and the response that were passed to the controller by the servlet container (thereby providing access to any specialized properties of the mapping itself as well as to the ServletContext).

Page 10: Struts PPT

10

Add-Ons

RequestProcessor Internals Process method called by ActionServlet Process calls a series of processXXX methods which perform

pre-defined preprocessing processActionCreate processActionForm processPopulate processValidate processActionPerform processException processForward processForwardConfig .

Page 11: Struts PPT

11

Road Ahead

The struts-config.xml file

Used to define and initialize resources like

ActionForms to collect input from users

ActionMappings to direct input to server-side Actions

ActionForwards to select output pages

DataSources for DB connections

Global Forwards

Global Exceptions

Page 12: Struts PPT

12

Road Ahead

ActionMapping

<action path="/TestAction" type=“com.wc.actions.TestAction">

name="AddressForm"     scope="request"     validate="true"     input="/pages/Address.jsp">

<forward name=“success" path="/pages/TestAction.jsp"/>

<forward name=“failure" path="/error/Error.jsp"/>

</action>

Page 13: Struts PPT

13

An ActionMapping defines a path that is matched against the request URI of the incoming request and usually specifies the fully qualified class name of an Action class

Contains where the request is coming from (sourcePage)

the name fo the ActionForm containing the user input

The Action class which should handle this request

The destination resource(s)

Page 14: Struts PPT

14

ActionForm

Encapsulates User input

Makes it easy to store and validate the data for an application's input forms

The framework sets the ActionForm's properties from the request parameters and sends the validated form to the

appropriate Action's execute method

Forget code like Integer.parseInt(request.getParameter

(“something”));

Page 15: Struts PPT

15

Action Class Has 2 methods-

public ActionForward execute(ActionMapping mapping, ActionForm form,

ServletRequest request, ServletResponse response)

throws Exception;

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse

response) throws Exception

Page 16: Struts PPT

16

Action Class Typical functionality contd..

Validate the current state of the user's session (for example, checking that the user has successfully logged on)

Validat form data, store the appropriate error message keys as a request attribute, and forward control back to the input form so that the errors can be corrected

Page 17: Struts PPT

17

Action class Typical functionality contd…

Perform the processing required to deal with this request

Update the server-side objects that will be used to create the next page of the user interface (typically request scope or session scope beans)

Return an appropriate ActionForward object that identifies the presentation page to be used to generate this response, based on the newly updated beans.

Page 18: Struts PPT

18

The Struts Framework – Architecture

Page 19: Struts PPT

19

Exception Handling

Define global exception handlers to execute when an Action class throws an Exception

Used to group generic exceptions in an application

Framewor takes care of forwarding to appropriate JSP on occurrence

Page 20: Struts PPT

20

Exception Handling contd

<global-exceptions>

<exception key="some.key"

type="java.io.IOException"

handler="com.yourcorp.

ExceptionHandler"/>

</global-exceptions>

Page 21: Struts PPT

21

Global Forwards

Forwards are instances of the ActionForward class returned from an Action's execute method

Map logical names to specific resources (typically JSPs), allowing you to change the resource without changing references to it throughout your application.

Typical usage- Forwarding to login pages

Page 22: Struts PPT

22

Global Forwards contd

<global-forwards type="org.apache.struts.action.ActionFor

ward">

<forward name="logon" path="/logon.jsp"

redirect="false" />

</global-forwards>

Page 23: Struts PPT

23

Struts validation framework

A single definition of validation rules for an application

Validation rules are loosely coupled to the application

Supports Internationalization.

Supports regular expressions

Page 24: Struts PPT

24

Struts validator framework contd…

validator.-rules.xml- defines the rule to be applied

Example- “required”

<validator name="required" classname="org.apache.struts.util.StrutsValidator"

method="validateRequired"

methodparams=“” msg="errors.required"/>

Page 25: Struts PPT

25

Struts validator framework contd…validaton.xml- tie the rule to the ActionForm<form-validation>

<formset>

<form name="checkoutForm">

<field property="firstName"

depends="required">

<arg0 key="label.firstName"/>

</field>

Page 26: Struts PPT

26

Why all this?

Clear separation between layers resulting In clear separation of roles and clear interface between programmers

View writer responsible for JSPs and ActionForms

Model writer provides his objects as DAOs or EJBs

Application writer concentrates on “strutting” it all together with Action Classes and the config file

Resulting in faster development

Page 27: Struts PPT

27

With Struts 1.2 we have the ability to maintain multiple config files to enable to divide a large aplication into modules

This further facilitates easy co-ordination between programmers in a large application

Page 28: Struts PPT

28

Easy to maintain- how?

Most varying parts of an application ar defined at 1 central place- The config file

The names of JSPs in ActionForwards

The exception handlers

The global forwards

The Action calss itself changes

Facility of using wildcards in mappings

Page 29: Struts PPT

29

Easy to maintain- Internationalization

All the Message resources of an app defined in Application.resources

For a new language add a locale specific Application.resources and use it.

Page 30: Struts PPT

30

Best Practices

Designing Action Classes Use Business Delegate Objects or DAOs to access

databases Don’t validate Business rules in the Action classes-

A mail acount registration example Key idea- Separation between Data and

Presentation of data Action Classes should only do data type validation

but should leave Business rule validations to the Business tier

Page 31: Struts PPT

31

Use DispatchAction for CRUD functions on same set of data

Use Javascript to modify a variable in the form to specify operation(C or R or U or D)<SCRIPT>function set(target) {document.forms[0].methodToCall.value=target;}</SCRIPT><html:submit onclick="set(‘insert');">SAVE

</html:submit><html:submit onclick="set(‘update');">

SAVE AS NEW</html:submitl>

Page 32: Struts PPT

32

Modify the Action Mapping to indicate dispatch variable

<action   path="/reg/dispatch"   type="app.reg.RegDispatch"   name="regForm"   scope="request"   validate="true"   parameter=“methodToCall"/>

Page 33: Struts PPT

33

Add “methodToCall” methods in the Action class public ActionForward insert(

    ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)   throws IOException, ServletException { ...

public ActionForward update(    ActionMapping mapping,     ActionForm form,     HttpServletRequest request,     HttpServletResponse response)   throws IOException, ServletException { ...

Page 34: Struts PPT

34

Use LookupDispatchAction for script free dispatch In our JSP, we can refer to the buttons in the usual

way  <html:form action="/test">

<html:submit><bean:message key="button.add"/></html:submit><html:submit><bean:message key="button.delete"/></html:submit></html:form>

Page 35: Struts PPT

35

LookupDispatchAction would have a method

protected Map getKeyMethodMap(ActionMapping mapping,    ActionForm form,    HttpServletRequest request) {  Map map = new HashMap();  map.put("button.add", "add");  map.put("button.delete", "delete");  return map;}

Page 36: Struts PPT

36

Screens with dynamic fields

Use String[] getProperty() and setProperty(String[]) methods

Use DynaActionForm

Page 37: Struts PPT

37

Safeguarding JSPs <web-app>

  <security-constraint>    <web-resource-collection>      <web-resource-name>no_access</web-resource-name>      <url-pattern>*.jsp</url-pattern>    </web-resource-collection>    <auth-constraint/>  </security-constraint> </web-app>

Page 38: Struts PPT

38

ActionForms- Coarse grained or fine grained

Fine-grained Too specific

Many in number

Ties records in database to view side

Coarse-grained Immune to changes in table structure

Better manageability

Page 39: Struts PPT

39

Use ResultObjects to return data to View

Result object is simply a transfer object equipped with methods designed to give the presentation layer a helping hand

Usually just a wrapper around some collection class int getSize() String getDescription() – Iterator getIterator()

Page 40: Struts PPT

40

Error Categorization

Register the errors under the appropriate category errors.add("fatal", new ActionError("....")); or

errors.add("error", new ActionError("...."));

Identify these messages and show them consistently

<logic:messagePresent property="error"> <html:messages property="error" id="errMsg" >    <bean:write name="errMsg"/></html:messages></logic:messagePresent >