• No results found

MODEL VIEW CONTROLLER ARCHITECTURE

In document Java Book Latest (Page 125-131)

SQL UNION ALL Example

MODEL VIEW CONTROLLER ARCHITECTURE

MVC Architecure:

MVC 1 --> presentation Logic and Application Logic is combined together. MVC 2 --> Presentation and Application logic is separated results in easy maintenance and updates.

MVC1 Flow.

Actions Happens here 1. Populate New Form 2. Call Reset() method 3. Call set() and get() 4. store desired scope 5. Validate

6. Action As directed by Programmer. STRUTS 1.2

--> a open Source F/W contain all kind of components. --> to build web applications easily and quickly.

--> Apache Software Foundation Part of Jakarta Products --> Based on MVC Design Pattern

--> Contains Approximately 250 Classes and Interfaces Follow Front Controller Design pattern.

Model --> Database View --> Response from/to Browser Controller --> ActionServlet. Basic Components --> Base F/W, JSTL, TILES Plug-in , Validator Plug-in

BASE FrameWork --> ActionServlet --> ControllerServlet. Controller Components :

ActionServlet --> Provided by F/W.

--> will populate class with data from the form.

User

Pwd

Submit

Reset

Servlet

JSP(View)

Jdbc()

Set()

Get()

DB

--> main controller class --> receive all HTTP Requests --> initializing struts framework --> to be configured in web.xml. RequestDespatcher --> Provided by F/W.

--> One Instance per application module processes all request per module --> Invoke proper action Instance

--> Default implementation provided by F/W ( can exist if necessary )  Should always forward or redirect to a resource once it completes STRUTS DATA FLOW

1) When a user submitted a jsp page. that page having (attribute of )action="login.do". the container will call to WEB.XML. in that web.xml thert is two section servlet And servlet mapping

2) In servlet mapping it find *.do in the url-pattern. if it found to take the name of servlet. and check the corresponding class. in the servlet section. that class is ActionServlet.

3) ActionServlet is the controller of Struts module architecture. in Action servlet having the service method. in that method we create RequestPrecessor class instance

4) Service(req,res) RequestPrecessor rp = new RequestPrecessor();

5) We call a process method of RequestProcessor class through the instance rp.process(req,res)

6) In the request processor class have the process method with the parameter of req,res. then it has 1 if condition in this class. that condition return always true. because that is dummy method.

7)Inside that condition ther is 6 steps are processing

a)Create a action mapping instance in the "Struts-Config.xml". it will kept all details of the action mapping path, value, type forward, validation=true/false, input ="*.jsp" etc these r created instance

b)Then it will create Form class instance before it check the name of action mapping and form name are coincidence or not if it same it will create form instance

c)Then it will go to ActionMapping instace the ris mention or not the validate =true/fale if false it will not execute the this step else it will execute this step.

d) Then it will create action instance

e) Next it will take four parameters of execute Method it will return ActionErrors instance. if it is not empty. it will go to error page other wise it will got to corresponding page. else if it is empty if will go further and display corresponding value of page in jsp view.This is struts flow.

BASIC FLOW OF STRUTS 1. Container loads web.xml

2. It loads actionservlet and Struts-config.xml configured in Web.xml.

3. In HTML While submitting we use <action path ="/login" type = "LoginAction"> through http://myhost/myapp/login.do . .do is configured in <url-pattern> as it should be directed to ActionServlet .

4. Here we give 2 possibilities namely Success / Failure.

5. If Success  the action tells the ActionServlet that the action has been successfully accomplished or vice- versa.

6. The struts knows how to forward the specific page to the concerned destination. The model which we want to use is entirely to you, the model is called from within the controller

components.

7. Action can also get associate with a JavaBean in our Struts configuration file. Java bean is nothing but a class having getter and setter methods that can be used to communicate between the view and the controller layer. These java beans are validated by invoking the validate() method on the ActionForm by the help of the Struts system. The client sends the request by the normal form submission by using Get or Post method, and the Struts system updates that data in the Bean before calling the controller components.

8. The view we use in the struts can be either Jsp page, Velocity templates, XSLT pages etc. In struts there are set of JSP tags which has been bundled with the struts distribution, but it is not mandatory to use only Jsp tags, even plain HTML files can be used within our Struts application but the disadvantage of using the html is that it can't take the full advantage of all the dynamic features provided in the struts framework.

The framework includes a set of custom tag libraries that facilitate in creating the user interfaces that can interact gracefully with ActionForm beans. The struts Jsp taglibs has a number of generic and struts specific tags tags which helps you to use dynamic data in your view. These tags helps us to interact with your controller without writing much java code inside your jsp. These tags are used create forms, internally forward to other pages by interacting with the bean and helps us to invoke other actions of the web application.

There are many tags provided to you in the struts frameworks which helps you in sending error messages, internationalization etc.

Note: The points we have described above will be in effect if and only if when the ActionServlet is handling the request. When the request is submitted to the container which call the ActionServlet, make sure that the extension of the file which we want to access should have the extension .do.

Jakarta Struts Framework --> open source implementation of MVC (Model-View-Controller)pattern for the development of web based applications.

ActionServlet--> The class org.apache.struts.action.ActionServlet is the called the ActionServlet that plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Extends javax.Servlet.HttpServlet Receive all F/W requests

Select proper appropriate module

Delegate request handle to request processor Instance One ActionServlet instance per <web-app>

Default implementation provided by F/W (can Exist if necessary)

Message Resources Definitions file Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message

Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag. <message-resources‏parameter=‖MessageResources‖‏/>

Action Class --> Need to be built by programmer.

--> The Action Class is part of the Model and is a wrapper around the business logic. --> Action Class is to translate the HttpServletRequest to the business logic.

--> extends Action override ActionForwards execute() return type --> Action Class all the database/business processing are done. --> EJB classes are handled using Late Binding of ejb class --> main controller class

--> receive all HTTP Requests --> initializing struts framework

--> to be configured in web.xml.

Action Mapping --> select instance form --> the Action form bean for Request if any REQ --> HTTPRequest for Processing

RES --> HTTPResponse for Processing

web.xml --> configure java web application properties of MiniHR app. struts-config.xml --> configure struts fw.

ApplicationResources.properties. --> externalize app strings, labels without recompile. import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class TestAction extends Action {

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request,

HttpServletResponse response) throws Exception { return mapping.findForward("testAction");

} }

ActionForm --> JavaBean that extends org.apache.struts.action.ActionForm maintains the session state for web application.

--> ActionForm object is automatically populated on the server side with data entered from a form on the client side.

--> If ActionForm Declared as Interface possibility for MisMatch underlying business tier instead of Strings, which violates one of the primary purposes for ActionForms in the first place (the ability to reproduce invalid input, which is a fundamental user expectation).

ActionForms as an interface would also encourage using existing DAO objects as ActionForms by adding implements ActionForm to the class. This violates the MVC design pattern goal of separation of the view and business logic.

ActionForm

Public class abcform extends ActionForm { // this is declared in form bean

}

public class abcAction extends Action { //methods

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException { Double price = null; // Default target to success

String target = new String("success"); if ( form != null ) {

String symbol = lookupForm.getSymbol(); price = getQuote(symbol);

}

// if price is null, set the target to failure if ( price == null ) {

target = new String("failure"); } else {

request.setAttribute("PRICE", price); }

// Forward to the appropriate View

return (mapping.findForward(target));

} }

DynaActionForms relieve developers of maintaining simple ActionForms. --> Extends org.Apache.Struts.action.ActionForm --> capture user Data from HttpServletRequest --> store Data Temporarily

--> Acts as a Fire-Wall between Presentation and Application Layer --> attributes /Arguments (Validation ,Reset)

--> ActionMapping , Request. ActionForm

ActionForm is used, then user himself has to write the setters and getters when ever he adds a control same process is repeated again and again when user creates a view

ActionForm generally contains user defined validations on form fields

DYNAACTIONFORM

DynaActionForm eliminates this burden and creates the form bean itself No bean class is required for the DynaActionForm and we will declare the form beans as DynaActionForm type in struts-confing.xml. with its properties. DynaActionForm doesn't contain validations on form fields i.e., where form field validations are

not required there DyanActionForm is used Validator Framework --> provides the functionality to validate the form data.

--> use to validate the data on the users browser as well as on the server side.

--> emits the java scripts and it can be used validate the form data on the client browser. --> Server side validation of form can be accomplished by sub classing your From

Bean with DynaValidatorForm

--> class get configured in validation.xml can be used for multiple operations. validator-rules.xml --> defines standard validation routines, reusable and used in validation.xml

--> error message key for validator tag. --> specify javascript code

--> run on browser to perform client side validations Validation.xml --> to define the form specific validations.

--> defines the validations applied to a form bean.

validation-key.xml --> specify a key stored in ApplicationResources.properties. --> This key is same across each loacal properties file.

<form-validation> <formset> <form‏name=‏‖‖> <‏field‏property‏=‖‏‖‏depends‏=‏‖required‖>‏</field>‏</‏formset>‏</‏form-validation> <html:javascript formName=javascript> Struts Validator

 Strut‘s‏validator‏frame‏work‏provides‏a‏number‏of‏‏built-in validations for all normal business requirements.

 The‏strut‘s‏validator-rules.xml contains the name of the validation rule and the associated in built method.

 validation.xml‏maps‏your‏forms‘‏fields‏with‏one‏or‏more‏validation‏rules,‏specified‏in‏‏validator- rules.xml.

 Your form bean should extend ValidatiorForm.

 ApplicationResources.properties, the resource bundle for internationalization, maps the keys to the respective values, for messages, labels, etc.,

 The validator plugin should be included in struts-config.xml to enable the use of the validator frame work by Struts controller.

 Struts Controller invokes the validator plugin and ensures that all the specified fields are validated.  In addition to the above, if you want your validation to take into account values in more than one

field, then you may override the validate() method of the ValidatorForm class.  Extend ValidatorForm. In your formbean class.

(org.apache.struts.validator.ValidatorForm)

public‏class‏InputFormAll‏extends‏ValidatorForm‏{….}  The ValidatorForm , in fact is a subclass of ActionForm .  It overrides the Validate() method of the ActionForm.

 Create your Action class which subclasses Action in the normal way. public‏class‏InputActionAll‏extends‏Action‏{…..}

 Create Resource Bundles with key / value pairs for the messages/ labels.(ApplicationResource.properties)

inputForm.userName=User name

inputForm.userName.mask={0} must start with a letter ………‏‏‏‏‏….‏

validateSsnum() --> conforms proper method signature for custom validations. --> perform actual validation logic.

Display validation fail errors on jsp page - < hml:errors> enable front-end validation based on the xml in validation.xml. -->

< html:javascript> < html:javascript

formName=‏‖logonForm‖‏dynamicJavascript=‏‖true‖‏staticJavascript=‏‖true‖‏/‏>‏

 generates‏the‏client‏side‏java‏script‏for‏the‏form‏―logonForm‖‏as‏defined‏in‏the‏validation.xml‏file.‏ Enable plugin in JSP use < plug-in> in struts-config.xml.

Struts Central collects and organizes links to all known Struts Resources, including articles,books, and third-party extensions, for Action, Shale, and Action 2.

Reload removed from Struts (since 1.1) --> ReloadAction in Struts was trying to act like a container, but it couldn't do a proper job of it.

--> It never did let you reload everything that you would really want to -- particularly changed classes -- so many people ended up having to reload the webapp anyway.

--> Containers are starting to offer reload-on-demand features which does the same thing as the Struts ReloadAction, only better.

--> Not supporting ReloadAction lets Struts avoid doing synchronization locks around all the lookups (like figuring out which action to use, or the destination of an ActionForward) so applications can run a little faster.

Action Servlet & Request Processor

Select Appropriate Module & handle it off to Request Process (Or) Load in Struts (Or)

Request Comes in Servlet , Select Appropriate Module Processing Done

1. Receive HttpServletRequest ( Handle Request )

2. Automatically populate a java bean from request parameter 3. Handle local and context type issues

4. Determine Action to invoke based URI provide extension Points Form Bean

Form bean is part of view layer Java Bean Java-Bean is the part of model layer MVC 2 Architecure Flow [ STRUTS]

In document Java Book Latest (Page 125-131)