Intorduction to struts
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Intorduction to struts

on

  • 2,585 views

This presentaion willl perfectly guide you to understand how MVC framework fits into J2EE Web Application and how Struts Framework emerged from MVC.

This presentaion willl perfectly guide you to understand how MVC framework fits into J2EE Web Application and how Struts Framework emerged from MVC.

Statistics

Views

Total Views
2,585
Views on SlideShare
2,585
Embed Views
0

Actions

Likes
1
Downloads
62
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Intorduction to struts Presentation Transcript

  • 1. Introduction To Struts By Anup Wadhekar @Gracioussoft Technologies,Pune E-mail : wadekaranup@gmail.com
  • 2.  Generic Web Application Architecture J2EE Web Application Architecture • CGI,Servlets and JSP • Model 1 Architecture • Model 2 Architecture - MVC • MVC with Configurable Controller Struts Architecture – First Look Struts Framework Components Struts Request Lifecycle Struts ‘Simple Hello World’ Example in Eclipse
  • 3. Generic Web Application Architecture
  • 4. Components of Generic Web Application  Client: Generally a browser(user agent) is controlled by a user to operate the Web application. The client’s functionality can be expanded by installing plug-in sandapplets.  Firewall: A piece of software regulating the communication between insecure networks (e.g.,the Internet)and secure networks(e.g.,corporate LANs). This communication is filtered by access rules.  Proxy: A proxy is typically used to temporarily store Web pages in a cache. However , proxies can also assume other functionalities, e.g., adapting the contents for users (customization), or user tracking.  Web server :A Web server is a piece of software that supports various Web protocols like HTTP and HTTPS, etc., to process client requests.  Database server: This server normally supplies an organization’s production data in structured form ,e.g., in tables.  Media server: This component is primarily used for content streaming of non- structured bulk data(e.g.,audio or video).  Content management server: Similar to a database server, a content management server holds contents to serve an application. These contents are normally available in the form of semi-structured data ,e.g., XML documents.  Application server: An application server holds the functionality required by several applications, e.g., workflow or customization.  Legacy application: A legacy application is an older system that should be integrated as an internal or external component.
  • 5. J2EE Web Application Architecture
  • 6. Why J2EE ?Technical Benefits• Enables component based approach to develop enterprise web application.• Reduces cost and complexity of developing large,multi-tier-web-based application.• Component types supported,State management,Database caching,declarative (automated) persistance,scalability through load balancing.Buisness Benefits•Indusrty buy-in and choice of vendors,greater utilization of existing IT assets.• Faster response to change,choice of proven ,scalable and reliable platform.
  • 7. Components of J2EE Web ApplicationClient Tier• Client tier supports both applet container and application client container.• Applet container is the container to manage the execution of applets.Exam- -ples of an applet container are applet viewer,web browser and java Plug-in running on the client together.• Application client container is the one which is responsible for managing theapplication client components. Both application client and its container residesat the client machine and are executed on the client end. Example ofapplication container is JVM.
  • 8. Components of J2EE Web Application Middle Tier• Whole presentation and buisness logic is executed in middle tier which con- sists of Web container , EJB container and a number of industry standered APIs for accessing Enterprise Information system and Database.• EJB Container Enterprise Java Beans (EJB) is a tecnology in J2EE platform,which standerdizes how to build server side components for distributed applications.It is a reusa- ble software components written in java,which run inside EJB Container.EJBcontainer is a part of J2EE application server which manages whole lifecycle of EJBs and provide them with some important system level services.When client sends request through JSP,JSP request EJB for information.Once EJB generate Information from database,JSP file then display it to client. EJB is NOT relevant to our discussion to Struts.
  • 9. Components of J2EE Web Application Middle Tier• Web ContainerIn Web Container also known as Servlet container,JSPs and Servlets are mainnon-pure java components mixed with plain static pages.They can alsogenerate dynamic HTML with dynamic contents coming from back end tier andinteract with client-tier components. In J2EE platform,the presentation between end user and system responseshould be handled by JSP and Servlets technologies and buisness logic shouldbe encapsulated by Java Bean (or Enterprise Java Bean).•Industry Standerd APIs are for accessing Enterprise Information system andDatabase. They include following services : 1)HTTP,HTTPs 2)Java Transaction API(JTA) 3)Java Interface Definition Language(JavaIDL) 4)Java Naming andDirectory Services (JNDI) 5)Java Message Services (JMS) 6)RMI-IIOP etc.
  • 10. Components of J2EE Web Application• Java EE Containers1) Application client container2) Applet Container3) Web container – part of Java EE Application Server4) EJB Container - part of Java EE Application ServerAll of the above comes under Java EE Containers.• Java EE Application Servers J2EE specification defines a whole lot of interfaces and a few classes.Implementations for these interfaces adhering to the J2EE specifications. These implementations are called J2EE Application Servers. Example : WebLogic by Oracle,WebSphere by IBM,Gerinomo,TomEE by Apache,Jboss etc
  • 11. CGI ,SERVLET AND JSPEvolution of Dynamic Content GenerationWhen World Wide Web (WWW) started in the year 1989 at he CERN laboratorythe idea was to have a mechanism which enabled sharing of researchinformation among researchers using hypertext docs. And hence Web wasdesigned to serve static contents in the beginning. The obvious and naturalprogression was to have the ability of dynamic content generation on Web andthere came the concept of CGI.CGI - Common Gateway InterfaceCGI was designed to generate the contents on the Web dynamically. It becamehugely popular in no time as it allowed the Web applications to access thedatabase to show results based on dynamically selected criterio and it alsofacilitated insert/update of information in the database accepting the info fromthe end-user.As the popularity grew the scalability of the web applications alsogrew and then we started realizing the limitaions of CGI.
  • 12. CGI ,SERVLET AND JSPLimitations of CGINew Process per Request - the main drawback of CGI approach was that itspawned a new heavy-weight Operating System process everytime a newrequest was made from the end users (from browser). This immenselyrestricted the scalability and responsiveness of the web applications as creating(and reclaiming once the request is served) OS processes are time and resourceconsuming stuff.Communication Gap between Web Server and Requests - sinceall the requests are executed in a different OS process from the Web Serverprocess hence it becomes difficult to have a smooth communication betweenthe server and the requests to handle stuff like logging, authorization, etc.Alternatives of CGI FastCGI,mod_perl,NSAPI,ISAPI Most important andPopular one :Java Servlets
  • 13. CGI ,SERVLET AND JSPJava Servlets - what are they?Sun Microsystems introduced this technology in the year 1997 and it became an instant hitdue to various advantages it provided over CGI. It was no longer required to have a newprocess every time a request was made from an end-user.It was a platform-independent (As it is written completely in Java), component-basedapproach of developing web applications having dynamic content genration capabilities.Since it is written in Java hence all the tested and tried rich set of APIs of Java are readilyavailable to be used and this advantage took this technology way above its competitors.
  • 14. CGI ,SERVLET AND JSP Example Servlet Code
  • 15. CGI ,SERVLET AND JSPJ2EE Web ApplicationAny web application that runs in the servlet container is called a J2EE webapplication. The servlet container implements the Servlet and JSP specification.It provides various entry points for handling the request originating from a webbrowser. There are three entry points for the browser into the J2EE webapplication - Servlet, JSP and Filter. You can create your own Servlets byextending the javax.servlet.http.HttpServlet class and implementingthe doGet() and doPost() method. You can create JSPs simply by creating atext file containing JSP markup tags. You can create Filters by implementing thejavax.servlet.Filter interface.The servlet container becomes aware of Servlets and Filters when they aredeclared in a special file called web.xml . A J2EE web application has exactlyOne web.xml.
  • 16. CGI ,SERVLET AND JSPWhy were JSPs needed when we had Servlets?Servlet DrawbacksServlets do an excellent job of dynamic content generation, but it becomes difficult andtedious to use Servlets for presentation of the data in HTML. EVery HTML change requiresus to recompile the Servlet and the maintenance of Servlets become difficult as HTMLchanges are quite frequest in nature and using Servlets to do that ends up makingcorresponding Java code changes everytime.Another serious drawback of this approach was that it didnt facilitate clear separationof roles and responsibilities. HTML design and devlopment is primarily the responsibilityof a Web Designer (usually a person having limited Java expertise) whereas theresponsibility of design & development of Servlets belongs to Java Developers. UsingServlets for presentaion of data mixed both these roles and hence the entire devlopmentlife cycle used to be more complex and hence slower. A clear separation of roles andresponsibilities enhanced the overall development cycle and it also made the applicationsbetter maintainable.
  • 17. CGI ,SERVLET AND JSPJava Server Pages (JSP) TechnologyJSP (JavaServer Pages) Technology is used to achieve the clear separation. A JSPcan use normal HTML tags/elements the way we can have in any other normalHTML file and in addition it can have Tags, Scriptlets, etc. to encapsulate thebusiness logic for the dynamic content generation. A Web Designer can simplyuse those tags or leave the scriptlets to be embedded by the Java Developers. Infact, its become a better practice to avoid scriptlets as much as we can from aJSP page and to rely only on Tags for the dynamic content generation. This notonly makes the life of JSP Page easier, but also enhances the reusability of thecode (writen for Tags) and hence improves maintanability.There are two models for developing JSP based web application architectures.• Model 1 Architecture• Model 2 Architecture (MVC)
  • 18. Model 1 Architecture
  • 19. Model 1 Architecture – How it Works  In this architecture a JSP Page is used not only for the display of the output to the client, but also for the entire request processing including Accepting the Request, Creating JavaBeans (or connecting to the DB for data), Executing the Business Logic to generate Dynamic Content, etc  Let us illustrate the operation of Model 1 architecture with an example. Consider a HTML page with a hyperlink to a JSP. When user clicks on the hyperlink, the JSP is directly invoked. This is shown in Figure 1.1. The servlet container parses the JSP and executes the resulting Java servlet. The JSP contains embedded code and tags to access the Model JavaBeans. The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string. In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page. The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags.
  • 20. Model 1 Architecture – Disadvantages  There is some separation between content (Model JavaBeans) and presentation (JSP). This separation is good enough for smaller applications. Larger applications have a lot of presentation logic.  The presentation logic usually leads to a significant amount of Java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers.  In large applications, JSPs are developed and maintained by page authors. The intermingled scriptlets and markup results in unclear definition of roles and is very problematic.  Application control is decentralized in Model 1 architecture since the next page to be displayed is determined by the logic embedded in the current page.Decentralized navigation control can cause headaches. All this leads us to Model 2 architecture .
  • 21. Restaurant – Analogy (Single Employee)
  • 22. It’s like coding everything in single servlet !
  • 23. Restaurant – Analogy (multiple employee)
  • 24. That sounds like MVC !
  • 25. Model 2 Architecture - MVC
  • 26. Model 2 Architecture – How it Works The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a Servlet. The following steps are executed when the user submits the request. 1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should point to the controller servlet). 2 .The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes). 3 .The Controller Servlet then by itself or through a controller helper communicates with the middle tier or directly to the database to fetch the required data. 4 . The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application. 5 . The controller then dispatches the request to the next view based on the request URL. 6. The View uses the resultant JavaBeans from Step 4 to display data.
  • 27. Model 2 Architecture – How it Works The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a Servlet. The following steps are executed when the user submits the request. 1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should point to the controller servlet). 2 .The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes). 3 .The Controller Servlet then by itself or through a controller helper communicates with the middle tier or directly to the database to fetch the required data. 4 . The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application. 5 . The controller then dispatches the request to the next view based on the request URL. 6. The View uses the resultant JavaBeans from Step 4 to display data.
  • 28. Model 2 Architecture – Advantages  No presentation logic in JSP, there are no scriptlets. This means lesser nightmares,although MVC does not architecturally prevent you from adding scriptlets.  With MVC you can have as many controller servlets in your web application, one Controller Servlet per module.  A single controller servlet for the web application lets you centralize all the tasks in a single place,avoids duplication of code.  Web applications based on Model 2 architecture are easier to maintain and extend since the views do not refer to each other and there is no presenta- -ion logic in the views.  It also allows you to clearly define the roles and responsibilities in large projects thus allowing better coordination among team members.
  • 29. Model 2 Architecture – Disadvantages Controller gone bad – Fat Controller  If MVC is all that great, why do we need Struts after all? The answercomplexities. the difficulties associated in applying bare bone MVC to real world lies in In medium to large applications, centralized control and processing logic in the servlet – the greatest plus of MVC is also its weakness.  Consider a mediocre application with 15 JSPs. Assume that each page has five hyperlinks (or five form submissions). The total number of user requests to be handled in the application is 75. Since we are using MVC framework, a centralized controller servlet handles every user request. For each type of incoming request there is “if” block in the doGet method of the controller Servlet to process the request and dispatch to the next view. For this mediocre application of ours, the controller Servlet has 75 if blocks. Even if you assume that each if block delegates the request handling to helper classes it is still no good. You can only imagine how bad it gets for a complex enterprise web application. So, we have a problem at hand. The Controller Servlet that started out as the greatest thing next to sliced bread has gone bad. It has put on a lot of weight to become a Fat Controller.
  • 30. MVC with Configurable Controller
  • 31. Configurable Controller Servlet Code Example Servlet Code
  • 32. MVC with Configurable Controller How It works 1. Properties file :It contains information in key value pair which is actually one to one mapping URL for each http request and handler class. There is a unique handler class for each url. 2 . Controller Servlet loads the properties file on startup 3 . When the HTTP request arrives from the client, the Controller Servlet looks up in a properties file to decide on the right Handler class for the HTTP request.This Handler class is referred to as the Request Handler. 4 . The Request Handler contains the presentation logic for that HTTP request including business logic invocation. In other words, the Request Handler does everything that is needed to handle the HTTP request. 5 . The only difference so far from the bare bone MVC is that the controller servlet looks up in a properties file to instantiate the Handlerinstead of calling it directly.
  • 33. MVC with Configurable Controller6. there must be some sort of commonality between the Request Handlersfor the servlet to generically instantiate the Request Handler. The commonal--ity is that all Request Handler classes implement a common interface. Let uscall this common interface as Handler Interface. In its simplest form, theHandler Interface has one method say, execute().7 . The Controller Servlet instantiates the Request Handler in the doGet()method and invokes the execute() method on it using Java Reflection. Theexecute() method invokes appropriate business logic from the middle tier andthen selects the next view to be presented to the user.8 . The controller servlet forwards the request to the selected JSP view. All thishappens in the doGet() method of the controller servlet. The doGet() methodlifecycle never changes.What changes is the Request Handler’s execute()method.9. You just saw how Struts works in a nutshell!!! Instead of using a propertiesfile like we did in this example, Struts uses XML to store more usefulinformation.
  • 34. Struts Architecture – First Look
  • 35. Struts Framework Components1. All the core components of Struts framework belong toController category.2. Struts has no components in the Model category.3. Struts has only auxiliary components in View category. Acollection of custom tags making it easy to interact with thecontroller. The View category is neither the core of Strutsframework nor is it necessary.However it is a helpful library forusing Struts effectively in JSP based rendering.
  • 36. Struts Framework ComponentsController CategoryThe ActionServlet and the collaborating classes form the controllerand is the core of the framework. The collaborating classes are :1.RequestProcessor2.ActionForm3.Action4.ActionMapping5 .Action Forward.View CategoryIt contains utility classes – variety of custom tags making it easyto interact with the controller. It is not mandatory to use theseutility classes. You can replace it with classes of your own.
  • 37. Struts Framework ComponentsModel CategoryStruts does not offer any components in the Model Category.Manycomponent models (CORBA, EJB) are available to implement thebusiness tier.NOTE: Some people argue that ActionForm is the model component.However ActionForm is really part of the controller. The Strutsdocumentation also speaks along similar lines. It is just View DataTransfer Object – a regular JavaBeans that has dependencies on theStruts classes and used for transferring the data to various classeswithin the controller.
  • 38. Struts Request LifecycleA request from the client browser creates an HTTP request which comes to the servletcontainer.Step 1 :Servlet container looks up into web.xml,using load-on-startup Instantiate theActionServlet and do following three tasks:First Task : The ActionServlet takes the Struts Config file name as an init-param.At startup, in the init() method, the ActionServlet reads the Struts Config file and loadinto memory.
  • 39. Struts Request LifecycleSecond Task : If the user types http://localhost:8080/app/submitForm.do inthe browser URL bar, the URL will be intercepted and processed by theActionServlet since the URL has a pattern *.do, with a suffix of "do".Because servlet-mapping is<servlet-mapping><servlet-name>action</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>Third Task : Then ActionServlet delegates the request handling to anotherclass called RequestProcessor by invokingits process() method.
  • 40. Struts Request LifecycleStep 2 :The RequestProcessor does the following in its process() methoda) The RequestProcessor looks up the configuration file for the URL pattern/submitForm (if the URL is http://localhost:8080/app/submitForm.do). andand finds the XML block (ActionMapping).ActionMapping from struts-config.xml
  • 41. Struts Request Lifecycleb) The RequestProcessor instantiates the EmpForm and puts it in appropriatescope – either session or request.The RequestProcessor determines theappropriate scope by looking at the scope attribute in the same ActionMapping.c) RequestProcessor iterates through the HTTP request parameters and populatesthe EmpForm.d) the RequestProcessor checks for the validateattribute in the ActionMapping.If the validate is set to true, the RequestProcessor invokes the validate() methodon the EmpForm instance.This is the method where you can put all the html form data validations.If Validate fail the RequestProcessor looks for the input attribute and return to JSPpage mentioned in input tag.If Validate pass goto next step.e) The RequestProcessor instantiates the Action class specified in theActionMapping (EmpAction) and invokes the execute() method on the EmpActioninstance.
  • 42. Struts Request LifecycleSignature of the execute method :f)Association of the logical name and the physical JSP page is encapsulated in theActionForward instance returned from the execute method.In return mapping.findForward("success") RequestProcessor looks for the successattribute and forward to JSP page mentioned in success tag. i.e success.jsp.In return mapping.findForward("failure")RequestProcessor looks for the failure attribute and forward to JSP page mentioned infailure tag. i.e. failure.jspIn J2EE terms, this is referred to as dispatching the view to the user.
  • 43. ‘Simple Hello World’ Example Requirements : Softwares 1. Eclipse IDE http://www.eclipse.org/downloads/ 2. Tomcat Server http://tomcat.apache.org/download-60.cgi 3. JDK www.oracle.com/technetwork/java/javase/downloads/index.html Libraries Struts 1.3 FILES XML Java 1.web.xml 1.HelloWorldAction.java 2.struts-config.xml 2.HelloWorldForm.java JSP 1.HelloWorld.jsp 2.index.jsp 3.failure.jsphttp://struts.apache.org/download.cgi
  • 44. Dynamic Web Project – Directory Structure
  • 45. web.xml
  • 46. struts-config.xml
  • 47. HelloWorldAction.java
  • 48. HelloWorldForm.java
  • 49. HelloWorldForm.java
  • 50. index.jsp
  • 51. HelloWorld.jsp
  • 52. failure.jsp
  • 53. STEPS TO EXECUTE 1. Create dynamic web project in eclipse 2. Add jsp,xml and java files according to directory structure. 3. Add struts libraries in Web-INF/lib folder. 4. Add same struts libraries in java build path(Right click on main project ->properties->java build path->libraries ->add external jar 5. Add tomcat server (Windows menu -> show view ->servers ->OK 6. Go to server wizard -> add new server - >Apache -> select the tomcat version you downloaded ->Next ->Browse ->select the folder where you extracted or installed the downloaded tomcat ->finish 7. After adding server,right click on Project-> Run as -> Run on Server ->select server you added ->Finish
  • 54. First run – On Startup
  • 55. Type ‘HelloWorld.do’ in url - Run
  • 56. return mapping.findForward(“failure”)
  • 57. THANK YOU !!!F EEDBACK : WADEKARANUP @ GMAIL . COM