Web Applications and Struts2

Embed Size (px)

Citation preview

  • 8/8/2019 Web Applications and Struts2

    1/24

    WebA lications

  • 8/8/2019 Web Applications and Struts2

    2/24

  • 8/8/2019 Web Applications and Struts2

    3/24

    Separationofapplicationlogicandmarkup

    Easierto

    change

    and

    maintain

    Lesserrorprone

    Accesstofunctionalitytosolveroutineneeds

    Datatransferbetweenclient HTTP andserver Java

    Validation

    Internationalization Userinterfacecomponents(tags)

  • 8/8/2019 Web Applications and Struts2

    4/24

    Struts2sitsontopoftwoimportanttechnologies

    Webframework (Struts2)

    HTTP

  • 8/8/2019 Web Applications and Struts2

    5/24

    Seriesofclientservermessageexchanges

    Designedfor

    static

    HTML

    rather

    than

    dynamic

    Stateless(howtodothingslikeauthentication?)

    Text based(howtomaptoandfromJavatypes?)

    Requestfor

    aresource

    Application or

    webserver

    Web

    browser

    Response

  • 8/8/2019 Web Applications and Struts2

    6/24

    ProvidesintuitiveobjectorientedabstractionofHTTP:

    Servlet(HttpServlet)

    SmallJavaprogram

    ReceiveandrespondtorequestsfromWebclients

    Objectrepresentingaclientrequest

    Accessto arameters re uestURL in utstream

    Response(HttpResponse)

    Objectrepresenting

    aserver

    response

    Accesstocontenttype,header,writer

  • 8/8/2019 Web Applications and Struts2

    7/24

    Session

    Provides

    a

    session

    between

    multiple

    requests

    AllowsServletstobindobjectsandmanipulateinformation

    Filter Performsfilteringonrequestsand/orresponses

    Configuredinweb.xml

    Useful

    for

    authentication,

    logging

  • 8/8/2019 Web Applications and Struts2

    8/24

    ServletsarepackagedintowebapplicationsasWARfiles

    Zip

    file

    with

    a

    specific

    structure on a ns:

    Servlets

    Webresources

    (HTML,

    CSS,

    templates,

    images)

    Dependentlibraries(JARs)

    / Web resources (HTML, CSS, templates, images) /WEB-INF Private files (not returned by Web server) /WEB-INF/web.xml Deployment descriptor / configuration file /WEB-INF/classes Java classes /WEB-INF/lib Depdendent libraries / JARs

  • 8/8/2019 Web Applications and Struts2

    9/24

    WebapplicationsaredeployedinServletcontainers

    Implementation

    of

    the

    Servlet

    specification

    PopularopensourceversionsareTomcatandJetty

    Servlet container

    http://localhost:8080/WebAppC/ServletB

    ServletA ServletC

    ServletB

    WebAppAServletB

    WebAppCServletB

  • 8/8/2019 Web Applications and Struts2

    10/24

    Solvingapplicationlevelconcerns/routinework!

    Binding

    request

    parameters

    to

    Java

    types

    Providinginternationalization

    Renderin resentationla er HTMLetc

    Makingcalls

    to

    business

    layer

  • 8/8/2019 Web Applications and Struts2

    11/24

    Purposes

    Encapsulates

    the

    work

    to

    be

    done

    for

    a

    request

    Determinewhichresultshouldrendertheview

    public class InvertStringAction implements Action{

    private String word;// set-method

    pr vate tr ng nverte or ;// get-method

    public String execute()

    { if word == null word.trim .len th == 0{

    return INPUT;}

    invertedWord = getInvertedWord(); // implemented another place

    return SUCCESS;

    }}

  • 8/8/2019 Web Applications and Struts2

    12/24

    ActionSupport:Abstract convenienceclassproviding:

    Validation

    Workstogetherwithinterceptorsinthedefaultstack

    ActionContext:Container

    holding

    relevant

    data

    for

    arequest:

    ValueStack

    Requestparameters

    Sessionvariables

    Applicationattributes

  • 8/8/2019 Web Applications and Struts2

    13/24

    Transfersdatadirectlyontomodelobjects

    Avoids

    tedious

    object

    creation

    code

    ProvidedbyinterfaceModelDriven

    xposesme o ge o e

  • 8/8/2019 Web Applications and Struts2

    14/24

    public class SaveStudentextends ActionSupport implements ModelDriven

    {

    private Student student = new Student();

    Class extending ActionSupport

    andimplementing ModelDriven

    Studentinstance created

    public Student getModel(){

    return student;}

    getModel implemented

    =

    public String execute(){

    studentService.saveStudent( student );

    Studentobject populated with

    dataandready touse

    return SUCCESS;}

    }Datawill beavailabe inview

    Dont changeobject reference!

  • 8/8/2019 Web Applications and Struts2

    15/24

    BasicvalidationaccessiblefromActionContext

    TheDefaultWorkFlowInterceptorworksbehindthescenes

    Separatesvalidation

    logic

    from

    business

    logic

  • 8/8/2019 Web Applications and Struts2

    16/24

    public class CalculateAction extends ActionSupport{

    private Integer numerator;

    private Integer denominator;// set-methods

    Class extending ActionSupport

    Javabean properties

    private Double result;// get-method

    public void validate()Validate method containing logic

    if ( denominator == null )

    {addFieldError( denominator, Please enter a numerator );

    }elseif ( denominator == 0 )

    Storingerrors viamethods

    provided byActionSupport

    addFieldError( denominator, Divison by zero not allowed );}

    }

    public String execute()

    Validation workflow separated

    fromexecution

    {result = // calculate somehow

    }}

  • 8/8/2019 Web Applications and Struts2

    17/24

    calculate.vmcalculate.vm

    Inputresult isusedwhen

    validation errors exist

    < m >

    #sform( "action=calculate" )#stextfield( "label=Numerator" "name=numerator" )#stextfield( "label=Denominator" "name=denominator" )

    Validation error messages printed

    forappropriate UI

    tag in

    view

    #ssubmit( "value=Calculate" )#end

  • 8/8/2019 Web Applications and Struts2

    18/24

    Separationlayerbetweensourcecodeandmessages

    Builtupon

    Java

    resource

    bundles,

    which

    will

    be

    found

    in:

    SamepackageandwithsamenameasActionclass

    Classpathaftersettingstruts.custom.i18n.resources configproperty

    ..

    LocaleaccessibleinJavacodethroughgetLocale()

    propertiesofUItags

  • 8/8/2019 Web Applications and Struts2

    19/24

    struts.xml configuration

    salute=Bonjour!

    i18n.propertiesini18nfolderon

    classpath

    Public class SaluteAction extends ActionSupport{

    public String execute(){

    Actionclass using getText(..)and

    getLocale()

    Locale locale = getLocale();return SUCCESS;

    }}

    #stext( "name=salute" )

    Velocity template using text tag

  • 8/8/2019 Web Applications and Struts2

    20/24

    HighleveltagAPIimplementedin:

    JSP

    Freemarker

    Datatags

    MovesdatabetweentheValueStackandtheview

    Controltags

    Altersthe

    rendering

    flow

    of

    the

    view

    UItags

    ProvidesadvancedHTMLformcontrols

  • 8/8/2019 Web Applications and Struts2

    21/24

    UsefultoapplydependencyinjectiontoaStruts2application

    Struts2Springpluginisrequired(struts2springplugin)

    .

    Classattribute

    in

    Struts

    2config

    will

    point

    at

    Spring

    bean

    identifiers

    Approach2:Useautowiringbyname

    Struts

    2

    will

    instantiate

    Actions

    but

    let

    Spring

    inject

    beans

    afterwards BeanidentifiersarematchedtosetmethodsinActions

  • 8/8/2019 Web Applications and Struts2

    22/24

    Only the StudentService bean is

    defined inthe configuration

    public class SaveStudentAction extends ActionSupport{

    Actionclass provides

    StudentService property andset

    methodpr vate tu ent erv ce stu ent erv ce;

    public voic setStudentService( StudentService studentService ){

    this.studentService = studentService;}

    Name of setmethod ismatched

    with Springbean identifiers

    // Student properties and setters

    public String execute()

    {.

    }

    }

  • 8/8/2019 Web Applications and Struts2

    23/24

    Struts2isbuiltupontheJavaServletspecificationwhichisbuiltuponHTTP

    ru s so vesapp ca on eve rou newor no prov e y

    theServletspecifiction

    Validatingdata

    Providinginternationalization

    Renderingpresentationlayer

    Makingcallstobusinesslayer

  • 8/8/2019 Web Applications and Struts2

    24/24

    Brown,Davis,Stanlick:Struts2inAction

    Velocityuserguide:

    http://velocity.apache.org/engine/devel/user guide.html

    Strutshomepage:

    . .