SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Web Development with
                                Apache Struts 2

                                Fabrizio Giudici

                                Tidalwave sas, CEO
                                NetBeans Dream Team

                                Senior Java Architect, Blogger


                                www.tidalwave.it
                                bluemarine.tidalwave.it
                                weblogs.java.net/blog/fabriziogiudici
                                stoppingdown.net




Nov 20, 2008   Web Development with Apache Struts 2                     1
Agenda
               ●   Java Web Frameworks
               ●   Struts basics
               ●   Struts 2
               ●   A small code example
               ●   Q&A




Nov 20, 2008             Web Development with Apache Struts 2        2
NetBeans 6.5 is out
               ●   Get it while it's hot! www.netbeans.org
                      –   Faster!
                      –   Compile-on-save, multithreading Java
                           debugger, visual deadlock indication
                      –   PHP support, JavaScript debugger and
                           library manager, better Spring /
                           Hibernate / JSF / JPA support
                      –   RESTful web services, SQL editor
                           improvements, JavaFX, Groovy and
                           Grails, Ruby and Rails improvements,
                           GlassFish v3
               ●
Nov 20, 2008               Web Development with Apache Struts 2   3
Java Web Frameworks
               ●   Question: how many Java web
                   frameworks are available?
                      –   1?
                      –   5?
                      –   10?
                      –   Dozens?




Nov 20, 2008              Web Development with Apache Struts 2   4
Java Web Frameworks
               ●   Answer: more than 50!
                       –   www.manageability.org/blog/stuff/how-
                            many-java-web-frameworks
               ●   Of course, those with a significant
                   spread are not so many
               ●   But choosing is difficult
               ●   NIH, but also radically different
                   approaches


Nov 20, 2008               Web Development with Apache Struts 2    5
My (subjective) take
               ●   Wicket
                       –   You really want to be agile
                       –   You routinely live on the leading edge
               ●   Tapestry
                       –   You like agile, but consolidated
               ●   Struts
                       –   You are “conservative” and like it easy
               ●   Java Server Faces
                       –   You love visual designers
                       –   You can survive to high complexity
Nov 20, 2008                Web Development with Apache Struts 2     6
JEE
               ●   JEE Web components:
                      –   “Foundation”: Servlet, JSP, Filter
                      –   “High level”: JSF
               ●   Foundation elements are enough, but
                   you're going to write tons of code
                      –   Validation, flow control, etc...




Nov 20, 2008               Web Development with Apache Struts 2     7
Struts
               ●   Struts 1 appeared in June 2001
                       –   Apache License
                       –   Strictly based on MVC pattern
                       –   Supported declarative validation, flow
                            control
               ●   Struts 2 is the “merge” of Struts 1 +
                   WebWork




Nov 20, 2008                Web Development with Apache Struts 2        8
MVC




Nov 20, 2008   Web Development with Apache Struts 2     9
Struts 2.x benefits
               ●   Actions are POJOs
               ●   Interceptors (from AOP)
               ●   Classes are now independent of HTTP
               ●   Simplified testing
               ●   Annotations, AJAX, Spring, Portlets,
                   etc...




Nov 20, 2008             Web Development with Apache Struts 2   10
Workflow




Nov 20, 2008   Web Development with Apache Struts 2          11
Components
               ●   web.xml
                      –   Installs a Filter on /*
               ●   struts.xml
                      –   Maps Action names
                      –   Defines the navigation flow
               ●   Actions
                      –   Execute a task
               ●   Views (JSP or others)
                      –   Render the UI
Nov 20, 2008               Web Development with Apache Struts 2     12
web.xml
               <?xml version="1.0" encoding="UTF-8"?>
               <web-app ... >
                   <filter>
                       <filter-name>struts2</filter-name>
                       <filter-class>
                           org.apache.struts2.dispatcher.FilterDispatcher
                       </filter-class>
                   </filter>
                   <filter-mapping>
                       <filter-name>struts2</filter-name>
                       <url-pattern>/*</url-pattern>
                   </filter-mapping>

                  ...

               </web-app>




Nov 20, 2008                Web Development with Apache Struts 2         13
A simple Action
         import com.opensymphony.xwork2.ActionSupport;

         public class MyAction extends ActionSupport {
             private final List<String> NBDTers = Arrays.asList(...);

               private String userName;
               private String message;

               public String getUserName() { return userName; }

               public void setUserName(String userName) {
                   this.userName = userName;
               }

               public String getMessage() { return message; }

               @Override
               public String execute() {
                   message = userName;
                   return NBDTers.contains(userName) ? "nbdt" : SUCCESS;
               }
          }
Nov 20, 2008                 Web Development with Apache Struts 2          14
struts.xml


               <struts>

                  <package name="/" extends="struts-default">
                    <action name="MyAction" class="myexample.MyAction">
                       <result name="input">/index.jsp</result>
                       <result name="success">/good.jsp</result>
                       <result name="nbdt">/nbdt.jsp</result>
                    </action>
                 </package>

               </struts>




Nov 20, 2008                 Web Development with Apache Struts 2            15
A simple view JSP
               <%@page contentType="text/html" pageEncoding="UTF-8"%>
               <%@taglib prefix="s" uri="/struts-tags" %>

               <html>
                 <body>
                   <h2>Welcome to JUG Lugano</h2>
                     Hello, <s:property value="message" default="Guest" />,
                      welcome to the first meeting of JUG Lugano!
                     <s:form method="GET" action="MyAction.action">
                        Would you be so kind to tell me your name?
                        <s:textfield name="userName" />
                        <s:submit value="Submit" />
                     </s:form>

                     <s:actionerror/>
                     <s:fielderror/>
                 </body>
               </html>


Nov 20, 2008                    Web Development with Apache Struts 2          16
Interceptors
               ●   Used to implement “common”
                   behaviours
                      –   Validations
                      –   Multiple submit filters
                      –   Logging
               ●   Pre-defined interceptors




Nov 20, 2008               Web Development with Apache Struts 2         17
Formal validation
                 ●    Declarative, save tons of code

               <validators>

                     <field name="userName">
                         <field-validator type="requiredstring">
                             <param name="trim">true</param>
                             <message>Your name is required.</message>
                         </field-validator>
                     </field>

               </validators>




Nov 20, 2008                   Web Development with Apache Struts 2      18
Interceptors
               ●   Code that is invoked across Actions
               ●   Many pre-defined interceptors
                      –   Parameter rename, cookie
                           management, component behaviours
                           (e.g. Checkboxes), background
                           actions
                      –   Validation itself is an interceptor




Nov 20, 2008               Web Development with Apache Struts 2         19
Custom interceptors


               public interface Interceptor
                 extends Serializable
                 {
                   public void destroy();

                    public void init();

                    public String intercept (ActionInvocation inv)
                       throws Exception;
                }




Nov 20, 2008                   Web Development with Apache Struts 2   20
Interceptors in
                                                            struts.xml

               <struts>

                  <package name="/" extends="struts-default">
                       <interceptors>
                           <interceptor name="logger" class="..."/>
                       </interceptors>
                    <action name="MyAction" class="myexample.MyAction">
                       <interceptor-ref name="logger"/>
                       <result name="success">/good.jsp</result>
                       <result name="nbdt">/nbdt.jsp</result>
                       <result name="input">/index.jsp</result>
                    </action>
                 </package>

               </struts>


Nov 20, 2008                 Web Development with Apache Struts 2         21
Conclusion
               ●   Robust, Struts 1 heritage
               ●   Keeps up with the latest standards
                   (POJOs, AOP, annotations, Spring, ...)
               ●   “Conservative” approach, but easy
               ●   Relevant sites:
                       –   struts.apache.org
                       –   beans.seartipy.com/2008/08/04/struts-
                            2-plugin-for-netbeans-ide-
                            nbstruts2support/

Nov 20, 2008               Web Development with Apache Struts 2       22

Mais conteúdo relacionado

Destaque

Destaque (9)

Bai 09 Basic jsp
Bai 09 Basic jspBai 09 Basic jsp
Bai 09 Basic jsp
 
Lecture6
Lecture6Lecture6
Lecture6
 
Struts2 in a nutshell
Struts2 in a nutshellStruts2 in a nutshell
Struts2 in a nutshell
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Struts
StrutsStruts
Struts
 
Struts2
Struts2Struts2
Struts2
 
Comparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and Wicket
Comparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and WicketComparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and Wicket
Comparing JSF, Spring MVC, Stripes, Struts 2, Tapestry and Wicket
 

Semelhante a Web Development with Apache Struts 2

Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
Peter Edwards
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
Fred Sauer
 
Real Time Web - What's that for?
Real Time Web - What's that for?Real Time Web - What's that for?
Real Time Web - What's that for?
Martyn Loughran
 

Semelhante a Web Development with Apache Struts 2 (20)

The Java alternative to Javascript
The Java alternative to JavascriptThe Java alternative to Javascript
The Java alternative to Javascript
 
GlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and FutureGlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and Future
 
Java EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the futureJava EE 6 & GlassFish v3: Paving path for the future
Java EE 6 & GlassFish v3: Paving path for the future
 
Getting started with Catalyst and extjs
Getting started with Catalyst and extjsGetting started with Catalyst and extjs
Getting started with Catalyst and extjs
 
Session 41 - Struts 2 Introduction
Session 41 - Struts 2 IntroductionSession 41 - Struts 2 Introduction
Session 41 - Struts 2 Introduction
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
Comparing JVM Web Frameworks - Devoxx 2010
Comparing JVM Web Frameworks - Devoxx 2010Comparing JVM Web Frameworks - Devoxx 2010
Comparing JVM Web Frameworks - Devoxx 2010
 
Java EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexusJava EE 6 & GlassFish v3 @ DevNexus
Java EE 6 & GlassFish v3 @ DevNexus
 
Java EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The FutureJava EE 6 : Paving The Path For The Future
Java EE 6 : Paving The Path For The Future
 
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
SF JUG - GWT Can Help You Create Amazing Apps - 2009-10-13
 
Spark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 WorkshopSpark IT 2011 - Java EE 6 Workshop
Spark IT 2011 - Java EE 6 Workshop
 
Learning jQuery @ MIT
Learning jQuery @ MITLearning jQuery @ MIT
Learning jQuery @ MIT
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Present and Future of GWT from a developer perspective
Present and Future of GWT from a developer perspectivePresent and Future of GWT from a developer perspective
Present and Future of GWT from a developer perspective
 
Struts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web ApplicationsStruts2 course chapter 1: Evolution of Web Applications
Struts2 course chapter 1: Evolution of Web Applications
 
Net Beans61 Ide
Net Beans61 IdeNet Beans61 Ide
Net Beans61 Ide
 
Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010Powering the Next Generation Services with Java Platform - Spark IT 2010
Powering the Next Generation Services with Java Platform - Spark IT 2010
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 
Real Time Web - What's that for?
Real Time Web - What's that for?Real Time Web - What's that for?
Real Time Web - What's that for?
 
Struts2
Struts2Struts2
Struts2
 

Mais de Fabrizio Giudici

NOSQL also means RDF stores: an Android case study
NOSQL also means RDF stores: an Android case studyNOSQL also means RDF stores: an Android case study
NOSQL also means RDF stores: an Android case study
Fabrizio Giudici
 
Tools for an effective software factory
Tools for an effective software factoryTools for an effective software factory
Tools for an effective software factory
Fabrizio Giudici
 
Parallel Computing Scenarios and the new challenges for the Software Architect
Parallel Computing Scenarios  and the new challenges for the Software ArchitectParallel Computing Scenarios  and the new challenges for the Software Architect
Parallel Computing Scenarios and the new challenges for the Software Architect
Fabrizio Giudici
 
blueMarine a desktop app for the open source photographic workflow
blueMarine  a desktop app for the open source photographic workflowblueMarine  a desktop app for the open source photographic workflow
blueMarine a desktop app for the open source photographic workflow
Fabrizio Giudici
 
blueMarine photographic workflow with Java
blueMarine photographic workflow with JavablueMarine photographic workflow with Java
blueMarine photographic workflow with Java
Fabrizio Giudici
 
blueMarine Sailing with NetBeans Platform
blueMarine Sailing with NetBeans PlatformblueMarine Sailing with NetBeans Platform
blueMarine Sailing with NetBeans Platform
Fabrizio Giudici
 
NASA World Wind for Java API Overview
NASA World Wind for Java  API OverviewNASA World Wind for Java  API Overview
NASA World Wind for Java API Overview
Fabrizio Giudici
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 
blueMarine Or Why You Should Really Ship Swing Applications
blueMarine  Or Why You Should Really Ship Swing  Applications blueMarine  Or Why You Should Really Ship Swing  Applications
blueMarine Or Why You Should Really Ship Swing Applications
Fabrizio Giudici
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
Fabrizio Giudici
 

Mais de Fabrizio Giudici (17)

Building Android apps with Maven
Building Android apps with MavenBuilding Android apps with Maven
Building Android apps with Maven
 
DCI - Data, Context and Interaction @ Jug Lugano May 2011
DCI - Data, Context and Interaction @ Jug Lugano May 2011 DCI - Data, Context and Interaction @ Jug Lugano May 2011
DCI - Data, Context and Interaction @ Jug Lugano May 2011
 
DCI - Data, Context and Interaction @ Jug Genova April 2011
DCI - Data, Context and Interaction @ Jug Genova April 2011DCI - Data, Context and Interaction @ Jug Genova April 2011
DCI - Data, Context and Interaction @ Jug Genova April 2011
 
NOSQL also means RDF stores: an Android case study
NOSQL also means RDF stores: an Android case studyNOSQL also means RDF stores: an Android case study
NOSQL also means RDF stores: an Android case study
 
Netbeans+platform+maven
Netbeans+platform+mavenNetbeans+platform+maven
Netbeans+platform+maven
 
Tools for an effective software factory
Tools for an effective software factoryTools for an effective software factory
Tools for an effective software factory
 
Parallel Computing Scenarios and the new challenges for the Software Architect
Parallel Computing Scenarios  and the new challenges for the Software ArchitectParallel Computing Scenarios  and the new challenges for the Software Architect
Parallel Computing Scenarios and the new challenges for the Software Architect
 
blueMarine a desktop app for the open source photographic workflow
blueMarine  a desktop app for the open source photographic workflowblueMarine  a desktop app for the open source photographic workflow
blueMarine a desktop app for the open source photographic workflow
 
blueMarine photographic workflow with Java
blueMarine photographic workflow with JavablueMarine photographic workflow with Java
blueMarine photographic workflow with Java
 
blueMarine Sailing with NetBeans Platform
blueMarine Sailing with NetBeans PlatformblueMarine Sailing with NetBeans Platform
blueMarine Sailing with NetBeans Platform
 
NASA World Wind for Java API Overview
NASA World Wind for Java  API OverviewNASA World Wind for Java  API Overview
NASA World Wind for Java API Overview
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
The VRC Project
The VRC ProjectThe VRC Project
The VRC Project
 
blueMarine Or Why You Should Really Ship Swing Applications
blueMarine  Or Why You Should Really Ship Swing  Applications blueMarine  Or Why You Should Really Ship Swing  Applications
blueMarine Or Why You Should Really Ship Swing Applications
 
Designing a JavaFX Mobile application
Designing a JavaFX Mobile applicationDesigning a JavaFX Mobile application
Designing a JavaFX Mobile application
 
Android java fx-jme@jug-lugano
Android java fx-jme@jug-luganoAndroid java fx-jme@jug-lugano
Android java fx-jme@jug-lugano
 
Mercurial
MercurialMercurial
Mercurial
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

Web Development with Apache Struts 2

  • 1. Web Development with Apache Struts 2 Fabrizio Giudici Tidalwave sas, CEO NetBeans Dream Team Senior Java Architect, Blogger www.tidalwave.it bluemarine.tidalwave.it weblogs.java.net/blog/fabriziogiudici stoppingdown.net Nov 20, 2008 Web Development with Apache Struts 2 1
  • 2. Agenda ● Java Web Frameworks ● Struts basics ● Struts 2 ● A small code example ● Q&A Nov 20, 2008 Web Development with Apache Struts 2 2
  • 3. NetBeans 6.5 is out ● Get it while it's hot! www.netbeans.org – Faster! – Compile-on-save, multithreading Java debugger, visual deadlock indication – PHP support, JavaScript debugger and library manager, better Spring / Hibernate / JSF / JPA support – RESTful web services, SQL editor improvements, JavaFX, Groovy and Grails, Ruby and Rails improvements, GlassFish v3 ● Nov 20, 2008 Web Development with Apache Struts 2 3
  • 4. Java Web Frameworks ● Question: how many Java web frameworks are available? – 1? – 5? – 10? – Dozens? Nov 20, 2008 Web Development with Apache Struts 2 4
  • 5. Java Web Frameworks ● Answer: more than 50! – www.manageability.org/blog/stuff/how- many-java-web-frameworks ● Of course, those with a significant spread are not so many ● But choosing is difficult ● NIH, but also radically different approaches Nov 20, 2008 Web Development with Apache Struts 2 5
  • 6. My (subjective) take ● Wicket – You really want to be agile – You routinely live on the leading edge ● Tapestry – You like agile, but consolidated ● Struts – You are “conservative” and like it easy ● Java Server Faces – You love visual designers – You can survive to high complexity Nov 20, 2008 Web Development with Apache Struts 2 6
  • 7. JEE ● JEE Web components: – “Foundation”: Servlet, JSP, Filter – “High level”: JSF ● Foundation elements are enough, but you're going to write tons of code – Validation, flow control, etc... Nov 20, 2008 Web Development with Apache Struts 2 7
  • 8. Struts ● Struts 1 appeared in June 2001 – Apache License – Strictly based on MVC pattern – Supported declarative validation, flow control ● Struts 2 is the “merge” of Struts 1 + WebWork Nov 20, 2008 Web Development with Apache Struts 2 8
  • 9. MVC Nov 20, 2008 Web Development with Apache Struts 2 9
  • 10. Struts 2.x benefits ● Actions are POJOs ● Interceptors (from AOP) ● Classes are now independent of HTTP ● Simplified testing ● Annotations, AJAX, Spring, Portlets, etc... Nov 20, 2008 Web Development with Apache Struts 2 10
  • 11. Workflow Nov 20, 2008 Web Development with Apache Struts 2 11
  • 12. Components ● web.xml – Installs a Filter on /* ● struts.xml – Maps Action names – Defines the navigation flow ● Actions – Execute a task ● Views (JSP or others) – Render the UI Nov 20, 2008 Web Development with Apache Struts 2 12
  • 13. web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app ... > <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ... </web-app> Nov 20, 2008 Web Development with Apache Struts 2 13
  • 14. A simple Action import com.opensymphony.xwork2.ActionSupport; public class MyAction extends ActionSupport { private final List<String> NBDTers = Arrays.asList(...); private String userName; private String message; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getMessage() { return message; } @Override public String execute() { message = userName; return NBDTers.contains(userName) ? "nbdt" : SUCCESS; } } Nov 20, 2008 Web Development with Apache Struts 2 14
  • 15. struts.xml <struts> <package name="/" extends="struts-default"> <action name="MyAction" class="myexample.MyAction"> <result name="input">/index.jsp</result> <result name="success">/good.jsp</result> <result name="nbdt">/nbdt.jsp</result> </action> </package> </struts> Nov 20, 2008 Web Development with Apache Struts 2 15
  • 16. A simple view JSP <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <html> <body> <h2>Welcome to JUG Lugano</h2> Hello, <s:property value="message" default="Guest" />, welcome to the first meeting of JUG Lugano! <s:form method="GET" action="MyAction.action"> Would you be so kind to tell me your name? <s:textfield name="userName" /> <s:submit value="Submit" /> </s:form> <s:actionerror/> <s:fielderror/> </body> </html> Nov 20, 2008 Web Development with Apache Struts 2 16
  • 17. Interceptors ● Used to implement “common” behaviours – Validations – Multiple submit filters – Logging ● Pre-defined interceptors Nov 20, 2008 Web Development with Apache Struts 2 17
  • 18. Formal validation ● Declarative, save tons of code <validators> <field name="userName"> <field-validator type="requiredstring"> <param name="trim">true</param> <message>Your name is required.</message> </field-validator> </field> </validators> Nov 20, 2008 Web Development with Apache Struts 2 18
  • 19. Interceptors ● Code that is invoked across Actions ● Many pre-defined interceptors – Parameter rename, cookie management, component behaviours (e.g. Checkboxes), background actions – Validation itself is an interceptor Nov 20, 2008 Web Development with Apache Struts 2 19
  • 20. Custom interceptors public interface Interceptor extends Serializable { public void destroy(); public void init(); public String intercept (ActionInvocation inv) throws Exception; } Nov 20, 2008 Web Development with Apache Struts 2 20
  • 21. Interceptors in struts.xml <struts> <package name="/" extends="struts-default"> <interceptors> <interceptor name="logger" class="..."/> </interceptors> <action name="MyAction" class="myexample.MyAction"> <interceptor-ref name="logger"/> <result name="success">/good.jsp</result> <result name="nbdt">/nbdt.jsp</result> <result name="input">/index.jsp</result> </action> </package> </struts> Nov 20, 2008 Web Development with Apache Struts 2 21
  • 22. Conclusion ● Robust, Struts 1 heritage ● Keeps up with the latest standards (POJOs, AOP, annotations, Spring, ...) ● “Conservative” approach, but easy ● Relevant sites: – struts.apache.org – beans.seartipy.com/2008/08/04/struts- 2-plugin-for-netbeans-ide- nbstruts2support/ Nov 20, 2008 Web Development with Apache Struts 2 22