Sunteți pe pagina 1din 47

Struts

XORIANT SOLUTIONS www.xoriant.com

Agenda
Introduction to Struts J2EE Application Model - View - Controller Struts in nutshell Features of struts Key components of struts Practical

      

Introduction to Struts


Created by Craig McClanahan and donated to Apache Software Foundation (ASF) in 2000 Current version 2.16 An open source framework for building Java web applications Implementation of the MVC model 2 Architecture Every struts application is an J2EE application

 

 

J2EE Application
In a simple request and response, the JSP file sets the data, controls the flow to the next page, and creates the HTML

JSP
Activities of join.jsp
 

Display opening input page. Read the email value from the form parameter. Validate the email address. Add the address to the database. Redirect to the next page.

JSP (contd..)
If email address is invalid: Set an error message. Redisplay join.jsp with the error message.

Drawbacks
Consequences of Single Page Approach


Heavy HTML and Java coupling The coder of the JSP file must be both a page designer and a Java developer. The result is often either terrible Java code or an ugly page, or sometimes both.

Embedded flow logic To understand the entire flow of the application, you have to navigate all of the pages. Imagine the pain of going through the logic on a 100-page Web site.

Debugging difficulties In addition to being ugly to look at, HTML tags, Java code, and JavaScript code all in one page makes it difficult to debug problems. Tight coupling Changes to business logic or data means possibly touching every page involved.

Why MVC ?
Facts to consider
In the example above using JSP we found that single JSP is running the show and is overloaded. It does the following jobs
  

Manage the users interaction with the system. Manage the actual data. Format the data in multiple ways and present it to the user. Hence this leads to the need for some design consideration, so that all three tasks can then be handled/done by different components.

Solution
This is where MVC design pattern comes to the rescue.

What is Design Pattern?

The expression Dont reinvent the wheel means that you shouldnt try to solve a common problem that many bright people have already faced and solved in a clever and elegant way

Design Pattern:
A design pattern is a blueprint for constructing a time-tested solution to a given problem. Its not a concrete implementation; rather, its a high-level design of how to solve a problem.

So, What is MVC ?




MVC is a design pattern that enforces the separation between the input, processing, and output of an application. It divides the application into three core components: Model View Controller

Each of these components handles a discreet set of tasks.

Model-View-Controller

MVC
The Three Pieces of MVC


Model

: The actual business data and logic

View

: Presentation / the pieces the user sees and interacts with

Controller : The ringmaster who know how to use the model to get something done

Features of MVC


Reliability:
The model and view have clear separation, which allows you to change the look and feel of an application without recompiling Model or Controller code.

Very low development and life-cycle costs:


The MVC makes it possible to have lower-level programmers develop and maintain the user interfaces.

Rapid deployment:
Development time can be significantly reduced because Controller programmers (Java developers) focus solely on transactions, and View programmers (HTML and JSP developers) focus solely on presentation.

Maintainability:
The separation of presentation and business logic also makes it easier to understand and modify. Parts are loosely coupled with each other.

MVC in picture
In the JSP Model 1 architecture, the JSP page alone processes the incoming request and replies to the client

The browser sends a request to a JSP page. The JSP page communicates with a model. The model is connected to a database. The JSP page responds to the browser.

JSP (modified)

Limitations of MVC model 1




There is no total separation between content (Model) and presentation (JSP)

 

Only for really simple and smaller application Application control is decentralized in this architecture (as the next page to be displayed is determined by the logic embedded in the current page)

Decentralized navigation control cause headaches when requirements keep changing Thus, the classical form of MVC needed to change, which leads to the Web adaptation of MVC, also commonly known as MVC Model 2 or MVC 2.

MVC Model 2
In the Model 2 architecture, the servlet processes the request, creates any beans or objects used by the JSP file, and forwards the request

1. The browser sends a request to a servlet. 2. The servlet instantiates a Java bean that is connected to a database. 3. The servlet communicates with a JSP page. 4. The JSP page communicates with the Java bean. 5. The JSP page responds to the browser.

Limitations with model 2


 

Difficult to maintain for very large application Leave us with duplicate code across all the different controllers in our app

A single MVC application will have many models, view and controllers So this shows that we need to improve controller.. Lets Jordon the controllers main task and see how we can handle it in better way

Improving the MVC controller

Designing our fantasy controller

Yes, its Struts in nutshell

Quiz
1. MVC is a _______________ 2. Give one liner for their role MODEL - ________ View - _________ Control - ________ 3. In Model 1 ____ process the request 4. In Model 2 _____ process the request 5. Controllers three main task ____ , _____, _____ 6. Every struts application is an __________ application

Quiz (answers)
1. MVC is a design pattern 2. Give onliner for their role MODEL - data/ buiseness logic View - presentation Control - controls the flow / get things done 3. In Model 1 JSP process the request 4. In Model 2 controller process the request 5. Controllers three main task: process request parameters, invoke model, dispatch View 6. Every struts application is an J2EE application

Features of Struts?
         

Takes much of the complexity out of building your own MVC framework Encourages good design practice and modeling Easy to learn and use Feature-rich Flexible and extensible Stable and mature Open source Integrates well with Java EE (J2EE) Good taglib support Works with existing web apps Unified error handling programmatically and declaratively

Key Components of Struts




Action Servlet (The Controller) This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.

The struts-config.xml File This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application. In it you will map: request URLs to Actions, Actions to Form beans and Actions to views

Action Classes It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.

Key Components of Struts (contd..)




View Resources View resources consist of Java Server Pages, HTML pages, JavaScript and Style sheet files, Resource bundles, JavaBeans, and Struts JSP tags.

ActionForms These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

Model Components The Struts Framework has no built-in support for the Model layer. Struts supports any model components: JavaBeans, EJB, any other.

web.xml
Web App Deployment Descriptor (web.xml)


Struts application is a Web application


Follows the same rule Has to have web.xml deployment descriptor

web.xml includes:
Configure ActionServlet instance and mapping Resource file as <init-param> servlet-config.xml file as <init-param> Define the Struts tag libraries

web.xml is stored in WEB-INF/web.xml

Example web.xml

struts-config.xml
  

Defines the set of rules for a Struts application Contains the configuration data to hook all the pieces together. Basic configuration tags
<global-exceptions> <global-forwards> <form-beans> <global-exceptions> <form-beans> <message-resources>

Example struts-config.xml

Behind the scenes .


When ActionServlet gets a request(/login), it will 1. 2. Find the action-mapping from struts-config that matches the filename from the url. If the mapping includes a name attribute, ActionServlet populates the form-bean identifed by the name (userForm). 3. If the mapping includes a type attribute (strutsdemo.struts.forms.UserForm), ActionServlet calls the execute() method of the Action (passing in the request, response, form-bean from item1, and a mapping object). 4. ActionServlet will then forward the request to the ActionForward(success/failure) returned by the execute method called in item 3. 5. If the mapping has a forward attribute, ActionServlet simply forwards the request to the url specified (if success then forward to /success.jsp and if failure then forwards to /failure.jsp). You cant specifiy type and forward for the same action. 6. If validation is set true, then if validation fails then the Action servlet forwards the request to url specified in input(/index.jsp) parameter

Flow Chart for struts

Struts flow Sample example


Lets now understand the flow of struts / how struts work with the help of an example. Steps for Sample example. 1. Login page should be displayed at start up. 2. User should be able to login with proper validation. 3. On successful login, welcome page should be displayed with the user name having a success message 4. If the login fails, the failure message should be displayed to user.

Action Servlet
Step 1 :
All struts based web application should contain the ActionServlet configuration in web.xml file. On load-on-startup the servlet container Instantiate the ActionServlet .

ActionServlet
 

It extends javax.servlet.HttpServlet It takes the Struts Config file name as an init-param. At startup, in the init() method, the ActionServlet reads the Struts Config file and load into memory.

If the user types http://localhost:8080/SampleApplication/login.do in the browser URL bar, the URL will be intercepted and processed by the ActionServlet since the URL has a pattern *.do, with a suffix of "do".

Then ActionServlet delegates the request handling to another class called RequestProcessor by invoking its process() method.

Action Servlet

Action Mapping
Step 2:

ActionServlet calls process() method of RequestProcessor.


The RequestProcessor does the following in its process() method: a) The RequestProcessor looks up the configuration file for the URL pattern /login (if the URL is http://localhost:8080/SampleApplication/login.do). and finds the XML block (ActionMapping). b) It then creates an object to ActionForm associated to that action mapped object

Action Form
Step 3 :

The RequestProcessor instantiates the 'loginForm' and puts it in appropriate scope - either session or request by looking at the scope attribute in the same ActionMapping. The RequestProcessor then iterates through the HTTP request parameters and populates the 'loginForm'.

Action Form
The RequestProcessor checks for the validate attribute in the ActionMapping. If the validate is set to true, the RequestProcessor invokes the validate() method on the LoginForm 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 (/login.jsp) and return to JSP page mentioned in input tag. If Validate pass it goes to next step.

Action Classes
Step 4 :

The RequestProcessor instantiates the Action class specified in the ActionMapping (LoginAction) and invokes the execute() method on the LoginAction instance. execute method performs the bussinesslogic which you provide and returns with an ActionForward key.

Action Forward
Step 5: Now the returned key (sucess/failure) is searched in the mapping object which is specified as forward tag. RequestProcessor looks for the appropriate view component(success.jsp/failure.jsp) and performs the getters on that view component and returns the response to the browser.

Advantages


Provides a controller ActionServlet that dispatches requests to the appropriate business actions (Action subclasses) provided by the application developer. All dispatching is defined in an XML file> (strutsconfig.xml).

Allows the input (data entry) JSP/Servlet to be specified for each Action subclass, so control can be returned to that JSP/Servlet in the case of an error.

Automates population of the JSP domain object (ActionForm subclass) with input data.

 

Data validation can be turned on or off in web.xml Open source framework

Disadvantages

  

Taglibs are hard to grasp Add complexity to application Data entry validation is toggled on/off on a global basis only (not on a per JSP/Servlet basis). Requires at least one additional class per deployed page: an Action subclass to invoke the corresponding business component or model behavior and forward control to the subsequent JSP/Servlet.

Quiz
7. Struts is an implementation of ________ architechture 8. Action servlet takes _______ as init parameter 9. web.xml must have an entry for ___________ 10. Action Servlet performs the role of __________ 11. In which method of Action class the business logic is executed? 12. Can we have more than one struts-config.xml file for a single Struts application? 13. How can we make message resources definitions file available to the Struts framework environment? 14. Any 5 Key components of struts:

Quiz(answers)
7. Struts is an implementation of MVC model 2 architecture 8. Action servlet takes struts-config as init parameter 9. web.xml must have an entry for action servlet 10. Action Servlet performs the role of controller 11. In which method of Action class the business logic is executed? execute () 12. Can we have more than one struts-config.xml file for a single Struts application? Yes 13. How can we make message resources definitions file available to the Struts framework environment? <message resources> in struts - config 14. Any 5 Key components of struts: Struts-config.xml, action servlet, action bean, action form, action mapping, action forward

References


Struts home page - http://jakarta.apache.org/struts

Reference book - http://www.scribd.com/doc/2910103/Struts-Survival-Guide

Questions

Questions ???

Thanks

Thanks You !!!


For any Doubts, Queries, Suggestions, Feedback, etc. please contact me at indarjeet.behari@xoriant.com

S-ar putea să vă placă și