Presentation Description

MVC architecture Struts introduction Action Class


Presentation Transcript



Introduction to MVC:

Introduction to MVC

The MVC Pattern:

The MVC Pattern MVC is a design pattern that facilitates development of scalable, flexible applications by segregating the application components into one of the following: Model View Controller

The Model:

The model refers to those components of the application that do the major work done by the application. In web application, models perform validation, implementation of web logic, write and read to and from the database. The Model components majorly serve the following purpose: Represent the business entities. Instances of the model are used to carry data around. Encapsulate functionalities provided by the application- Database reading and writing validation etc. Decide the flow of execution of the application. Usually the methods of the models decide the line of execution. The Model

Model-The engine of an application:

Model-The engine of an application Models are the engine of the application. They contain most of the code for what the application does. They are the busiest code in an application

The View:

View refers to the application’s face. It refers to that component or group of components with which the user interacts. When a user accesses/interacts with a web application, he/she does it through web pages that are part of the web application. These pages constitute the view. Views are generally used for the following purpose: Representing data entry forms. Representing reports-Tabular display of data. The View

View-The Control Panel:

View-The Control Panel Views are like the control panel. They are interfaces through which data is entered. They also show results. Views are what the data users see and experience in a web application.

The Controller:

The controller’s primary task is to act like a router. It moves data around the application in the form of objects of the model. It is also responsible for initiating the execution of model’s methods. After initiating the execution, the controller figures out the result of the execution and accordingly renders an appropriate view to the user. The Controller

Controller-The Wiring:

Controller-The Wiring Controller is the wiring of the web application. Responsible mainly for data routing and also making the application run along a certain path of execution.

How it all works…:

How it all works…

Advantages of the MVC Pattern:

MVC pattern helps us achieve loose coupling by dividing the application into the model, view and controller components. Since the model and controller are independent of the view, one view technology can easily swapped for the other, application is not very affected in case of such a view. Advantages of the MVC Pattern

What is Struts:

What is Struts

What is Struts?:

Implementation of the MVC pattern done by Apache Software Foundation. Web application development framework. Based on java technologies like Servlets, JSP, Java Beans Present in two major flavors: Version 1.x Version 2.x Provides rich libraries that automate several tasks involved in developing web applications like AJAX, validation etc. What is Struts?


Developed by Craig McClanaghan Donated to the Apache Software Foundation in the year 2000 Ever since had been used in numerous projects across the world and has been accepted as the web development framework of choice. Early 2005, WebWork project spun off from struts framework. WebWork and Struts merge together in Feb 2007 and remerged as struts 2. Current Version 2.3.1 Struts-History

The Struts way of doing things:

Struts is a java based MVC implementation. Java technologies have been used in realizing the model, the view and the controller. These components are implemented through the following: Model-Action Classes(Simple classes also known as POJO’s) View-JSP Pages Controller-Servlet Filter The Struts way of doing things

Model-Action classes:

Models in Struts are normal Java classes. These classes usually have properties to hold data. For instance the data posted by a form is held in an Action class via the member variables. These classes also have methods that contain the business logic of the application like validation, saving data to database or retrieve data from the perspective of the application etc. These methods may themselves do the task or call methods present in other classes, just to introduce modularity. The methods return a string that represents the result of the activity performed by the method. Model-Action classes

Building an action class:

Action classes are simply java classes. So they need not extend or implement any class or interface as such. There are classes and interfaces however in the Struts library that make the task of creating action classes a little simpler. Often action classes may also inherit from either: The Action interface The ActionSupport class(which in turn implements the Action interface) Inheriting from the Action interface or ActionSupport class provides utility functions for doing stock activities like validation etc. Building an action class

Building the Action class(Contd.):

let us proceed for building our first Hello World struts2 project. The aim of this project is to build a web application that collects the user's name and displays "Hello World" followed by the user name. Building the Action class(Contd.)

The Action class:

public class HelloWorldAction{ private String name; public String execute() throws Exception { return "success"; } public String getName() { return name; } public void setName(String name) { = name; } } The Action class

Building the View:

Views are one of the most beautiful aspect of Struts framework. Views are JSP pages. Views may be forms or reports. Struts provides a rich set of tags(struts-tags) that make creating forms and incorporating validation into them easier than plain JSP. So, lets go ahead and create a file-HelloWorld.jsp in our project Building the View

Building the view(Contd.):

<%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>Hello World</title> </head> <body> Hello World, <s:property value="name"/> </body> </html> Building the view(Contd.)

PowerPoint Presentation:

We also need to create one page “index.jsp”. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call the a defined method of the HelloWorldAction class and render the HelloWorld.jsp view. <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""> <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World From Struts2</h1> <form action="hello"> <label for="name">Please enter your name</label><br/> <input type="text" name="name"/> <input type="submit" value="Say Hello"/> </form> </body> </html>

Building the controller:

Finally comes the controller Well very less often do we build controllers. The struts libraries provide us with a controller that does almost all that needs to be done. The controller is a Servlet filter by the name: FilterDispatcher. All that we need to do is configure the web app in such a manner that, all requests are routed through the FilterDispatcher. The FilterDispatcher is configured using an xml configuration file that goes by the name struts.xml. Its contained in WEB-INF. Primarily it contains the various possible outcomes of actions and the target the outcomes map to. Building the controller

Configuring the Controller:

In order to configure the controller add the following code to the web.xml file. <?xml version="1.0" encoding="UTF-8"?> <web-app> <display-name>Struts 2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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> This would make sure all requests that are received by the web server are route through the filter(Controller). Configuring the Controller

The Struts configuration file:

We are almost done but there is one last thing that needs to be done i.e. wiring the action class up to the rest of the application. Forms can easily submit data to JSP pages or servlets. In case we want the data to be submitted to an Action class, we need to route it through the FilterDispatcher. The FilterDispatcher looks up the struts configuration file and decided which Action class has to be instantiated and whose method has to be called. Configuration information related to Action classes are stored in the struts.xml file. This file should be present in the same place where other classes are stored, i.e. /WEB-INF/classes. The Struts configuration file

The struts configuration file(Contd.):

Type the following code into the struts.xml file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" ""> <struts> <constant name=" struts.devMode " value="true" /> <package name=" helloworld " extends="struts-default"> <action name="hello“ class="com.tutorialspoint.struts2.HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts> The struts configuration file(Contd.)

The struts configuration file(Contd.):

Code mentioned in previous slide defines an action called HelloWorldAction. For this action’s execute method, if the string “success” is returned then HelloWorld.jsp is dispatched to the client. There can be more than one results of the action all defined within the action tag. The struts configuration file(Contd.)

Deploy and Run:

Finally the application can be deployed and executed. Some error scenarios: Tomcat startup errors may be due to: Wrong data in struts.xml or web.xml Incompatible jar files in the lib folder Resource not found errors may be again due to the same reasons. So please check web.xml and struts.xml files. Deploy and Run

Struts Action Classes:

Struts Action Classes

The Action class:

One of the good things in Struts 2.x is that Action classes need not be special. They can be normal classes(classes that do not inherit any other class or interface) You may however at times create Action classes by: Inheriting the Action interface Extending the ActionSupport class. The action class also may have methods other than the execute method that can be invoked by the FilterDispatcher, provided its name is present in the struts.xml file. The Action class

Inheriting Action:

Action classes that implement the Action interface inherit five variables: public static final String SUCCESS=“success” public static final String NONE=“none” public static final String ERROR=“error” public static final String INPUT=“input” public static final String LOGIN=“login” These variables are symbolic of what next should happen after the action class method is executed. They can be returned from the methods and appropriate mapping provided in the struts.xml file. Inheriting Action

Inheriting Action(Contd.):

The following table lists the constants and their meanings: Inheriting Action(Contd.) Result Meaning/Description SUCCESS The action was successful. NONE The action was successful but do not show a view. ERROR The execution failed. INPUT The action requires more input before it can be executed. LOGIN The action could not be completed as the user is not logged in.

Inheriting Action(Contd.):

The Action interface also contains the definition of the execute method: Public String execute() throws Exception So in case you are implementing this interface to create the action class, you need to override this method. It’s a good practice to implement this interface because that way we can be sure that our class contains an execute() method. There is a disadvantage however. To compile such a class, the classpath needs to be set to point to the jar file that contains the Action interface. Inheriting Action(Contd.)

Inheriting Action Support:

The ActionSupport class implements the Action interface and provides blank implementation for the execute() method. Apart from Action, the ActionSupport class also implements the following interface: Validateable ValidationAware TextProvider LocaleProvider Serializable Inheriting Action Support

The Validateable Interface:

This interface contains the validate() method. The definition is: Public void validate() A blank implementation is provided in the ActionSupport class. In our Action classes, this is where validation of the values should be done. The Validateable Interface

The Validation Aware Interface:

This interface contains an assortment of methods that a class should have if its capable of storing validation messages. Few of the methods are: addActionError(String message)- This function is called to log an error message for the action. addActionMessage(String message) -Log a message for this action. Collection<String> getActionErrors() -Retrieves the error messages for this action. Can be used in views to retrieve the error messages that were logged related to the action. Collection<String> getActionMessages() -Retrieves the messages for this action. The Validation Aware Interface

The Validation Aware interface(Contd.):

addFieldError(String FieldName, String message) - This method adds an error message for a particular field. Useful when we want to show message in the form for fields. Map<String, List<String>> getFieldErrors – This method returns the error messages logged for the various fields. Again used in views to retrieve the error messages for individual fields. The Validation Aware interface(Contd.)

TextProvider and LocaleProvider interface:

These interfaces provide support for globalization and localization. The TextProvider interface has method for loading resource bundles. The actual implementation has to be provided by the inheriting class. The LocaleProvider interface has methods to retrieve current locale. Again the actual implementation has to be provided by the inheriting class. TextProvider and LocaleProvider interface

Serializable interface:

The Serializable interface allows for persisting the action class instances to streams. Particularly useful if the objects data has to be persisted to files rather than to the database management system. Serializable interface

Action class extending ActionSupport:

import com.opensymphony.xwork2.ActionSupport; public class Login extends ActionSupport{ String username ,password; // Getters and Setters public void validate() { if(username==null||username.length()==0) addFieldError(“username”, ”Username cannot be left empty, please enter valid username”); if(password==null||password.length()==0) addFieldError(“password”, ”Password cannot be left empty , please enter valid username”); } public String execute() { return “success”; } } Action class extending ActionSupport


Understanding the advantages of MVC pattern for designing application. Clearly understand the advantages of using the Struts 2.x for building web applications Understand the usage of Model, View and Controller components of Struts 2.x framework. Build web applications that use the features of Struts 2.x framework Summary

Thank You:

Thank You

authorStream Live Help