0% found this document useful (0 votes)
143 views34 pages

Welcome To All: Gop I

The document provides an introduction to the Model-View-Controller (MVC) framework and the Struts framework. It discusses how Servlets and JSPs work, problems with the early JSP implementation, and how MVC addresses these problems through separating the model, view, and controller responsibilities. It then introduces the Struts framework as an implementation of the MVC pattern, describing how it uses actions, forms, and tag libraries to link the model (data) to the view (HTML) via a controller. The document outlines the basic components and flow in Struts applications to connect the user interface with the application logic and data.

Uploaded by

arya_accent
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
143 views34 pages

Welcome To All: Gop I

The document provides an introduction to the Model-View-Controller (MVC) framework and the Struts framework. It discusses how Servlets and JSPs work, problems with the early JSP implementation, and how MVC addresses these problems through separating the model, view, and controller responsibilities. It then introduces the Struts framework as an implementation of the MVC pattern, describing how it uses actions, forms, and tag libraries to link the model (data) to the view (HTML) via a controller. The document outlines the basic components and flow in Struts applications to connect the user interface with the application logic and data.

Uploaded by

arya_accent
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 34

Welcome to All

opi
G
Introduction to MVC and
Struts Framework
Outline
Background (Servlets and JSPs)
JSP Design
MVC
Struts
Into the Future
Outline
Background (Servlets and JSPs)
JSP Design
MVC and JSP Model 2
Struts
Into the Future
Client (HTTP) Request

Server (HTTP) Response

Web Browser Web Server


(Client) (Servlet Container)
Working of Servlet
A client Sends a request to a Servlet container, which acts the web
server, through the a web browser

The web server searches for the required servlet and initiates it

The servlet then processes the client request and sends the
response back to the server, which is then forward to the client

“Servlet is server side component which takes the client request ,


process the request and gives the response to the client”
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SimpleServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException
{
PrintWriter out;
String title = "Simple Servlet Output";

// set content type and other response header fields first


response.setContentType("text/html");

// then write the data of the response


out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println(title);
out.println("</TITLE></HEAD><BODY>");
out.println("<P>This is the output from SimpleServlet.");
out.println("</BODY></HTML>");
out.close();
}
}
JSP file

Generated
Pre-processed Servlet

Servlet
Compiled .class file
JSP
Snippets of Java in HTML
Processed into servlets
Display easier to maintain
Much like ASP
"JSP technology should be viewed as the norm while
the use of servlets will most likely be the exception."
(Sun in 1999)
JSP
<%@ page info="Books" errorPage="error.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Book Page</title></head><body>
<h1>Book Form</h1>
<jsp:useBean id="bookBean" class="BookForm" scope="request"/>
<table>
<tr><td>Title:</td>
<td><input name="title" type="text" value='<jsp:getProperty name="bookBean" property="title"/>'</td></tr>
<tr><td>Author:</td>
<td><input name="author" type="text" value='<jsp:getProperty name="bookBean" property="author"/>'></td></tr>
<tr><td>Publisher:</td>
<td><input name="publisher" type="text" value='<jsp:getProperty name="bookBean"
property="publisher"/>'></td></tr>
<tr><td>Year:</td>
<td><input name="year" type="text" value='<jsp:getProperty name="bookBean" property="year"/>'></td></tr>
<tr><td>URL:</td>
<td><input name="url" type="text" value='<jsp:getProperty name="bookBean" property="url"/>'></td>
</table>
<A HREF="/clearBook.jsp">Clear form</A><BR>
Problems with JSP
Mixing of code and display still not easy to maintain
Tempting to put too much Java code in the JSP
(tightly coupled)
Embedded logic flow
Difficult to debug
Still no framework for designing a web application
Problems with JSP Model I
Uses much scriplet code in JSP
Pages can be large and complicated
Still embeds navigation in page
Boundaries of responsibility are still unclear.
Tends not to be modular

“To avoid the problems in JSP Model I we use MVC architecture “


What is MVC?
A design pattern used to separate business logic from user
interface, from program flow. The MVC (Model-View-
Controller) architecture is a way of decomposing an
application into three parts: the model, the view and the
controller. It was originally applied in the graphical user
interaction model of input, processing and output.
View
How data is presented to the user
Model
Data or state within the system
Controller
Connects the model and the view. Handles program
flow.
Introduction of Struts 2 Framework
Latest version : Struts 2.2.1v
General availability Release : 16 Aug 2010
 Version used : Struts 2.0.14v
General availability Release : 24 Nov 2008
  
Platform Requirements
 Apache Struts 2 requires :Servlet API 2.4v,JSP API 2.0v & Java 5v or 6v

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java


web applications. The framework is designed to streamline the full development cycle,
from building, to deploying, to maintaining applications over time.
 
Apache Struts 2 was originally known as WebWork 2. After several years, the
WebWork and Struts communities joined forces to create Struts 2.
Struts 2 is a MVC framework i.e. the data that is to be displayed to user has to be
pulled from the Action.
•Framework is a tool used to design as per requirements and is a collection of
classes and Libraries.
MVC I (Page-Centric)Architecture

There is no clear distinction between view and a controller. In Java terms, there is
JSP page (view and partial controller) which itself controls Business logic (Model)
that is why it is also called as page-centric architecture.
MVC II (Servlet-Centric)Architecture

MVC2 incorporates a clear separation of view and controller. A controller receives


all the requests, retrieves data from a Model and forwards it to next view for
presentation. 
In Java terms, there is a central Servlet (Controller) which calls business logic
(Model) and the forwards it particular JSP page (View) that is why it is also called
servlet-centric architecture
The View
 The view is how data is represented to the user. For instance
the view in a web application may be an HTML page, an
image or other media
The Model
 The model represents the data in the system. For instance, a
model might represent the properties associated with a
user’s profile
The Controller
 The controller is the glue between the model and the view.
It is responsible for controlling the flow of the program as
well as processing updates from the model to the view and
visa versa
Struts Components
Controller – The ActionServlet is responsible for
dispatching all requests. Mappings to actions are
defined in the struts-config.xml file
Action – Actions are defined by extending the
Action class. Actions perform actual work.
Model – The ActionForm can be extended to
provide a place to store request and response
data. It is a JavaBean (getters/settters)
View – JSP pages utilizing Struts tag libraries.
Struts Flow
Business
create ActionForm
Controller Layer

Http Event
ActionServlet dispatch Business
Logic

Browser Struts- Action


Config. create/set
forward xml

Model
forward Resource
Bundle
JavaBean
Http Response View
get
JSP
Struts: The Model
To define a model in Struts is simple. Just create a java class
and provide some functions.
Your model classes should be coded independent of the Struts
framework to promote maximum code reuse by other
applications (i.e. if you have to reference javax.servlet.*
class in your model, you are doing something wrong)
Struts provides some default Model components, the most
important of which is ActionForm.
If you create a Model class by extending the Struts ActionForm
class, Struts will
 Ensure your form bean is created when needed
 Ensure form submittal directly updates your form object with the
inputted values
 Your controller object will be passed the form bean
Model: ActionForm
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

public class LogonForm extends ActionForm {


protected String userName;
protected String password;

public void setUserName(String userName) {


this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
//There would also be getters for these properties
}
Model: Action Form (cont…)
When this “LogonForm” is associated with a controller, it will
be passed to the controller whenever it’s service is requested by
the user.
JSP pages acting as the view for this LogonForm are
automatically updated by Struts with the current values of the
UserName and Password properties.
If the user changes the properties via the JSP page, the
LogonForm will automatically be updated by Struts
But what if the user screws up and enters invalid data?
ActionForms provide validation…
Before an ActionForm object is passed to a controller for
processing, a “validate” method can be implemented on the
form which allows the form to belay processing until the user
fixes invalid input as we will see on the next slide...
Model: ActionForm Validation
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
if (“”.equals(this.userName)) {
ActionErrors aes = new ActionErrors();
aes.add(new ActionError(“error.username.invalid”));
return aes;
}

Typically what will happen is Struts will see that errors are being
returned and will forward the user to a jsp page that has been setup as
the “failure” page.
Usually, the errors result from bad input on a form, so the failure page
will be set to the original form and any <html:errors> tags which are
found are replaced with the contents of the ActionErrors returned from
the validate method.
The Controller
The controller is the switch board of MVC.
It directs the user to the appropriate views by providing the view
with the correct model
The task of directing users to appropriate views is called
“mapping” in struts.
Luckily, the Struts framework provides a base object called
org.apache.struts.action.ActionServlet.
The ActionServlet class uses a configuration file called struts-
config.xml to read mapping data called action mappings
The ActionServlet class reads the incoming URI and tries to
match the URI against a set of action mappings to see if it can
find a controller class which would be willing to handle the
request
This process is described in a diagram on the following page
http://myhost/authorize.do

Server configured to pass *.do extensions to


org.apache.struts.action.ActionServlet
via a web.xml configuration file

ActionServlet object inspects the URI and tries to match it


against an ActionMapping located in the struts-config.xml file.

Instance of appropriate Action class is found and it’s perform() method is called

Action object handles the request and returns control to a view based where the user is within
the flow of the application
public class LogonAction extends Action {

public ActionForward perform(ActionMapping mapping,


ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {

LogonForm myForm = (LogonForm) form;

if (myForm.getUserName().equals(“john”) &&
myForm.getPassword().equals(“doe”)) {

//return a forward to our success page


return mapping.findForward(”success”);
} else {
ActionErrors errors = new ActionErrors();
errors.add("password",
new ActionError("error.password.required"));
this.saveErrors(errors); //Action implements this method
//go back to the page that made the request
return (new
ActionForward(mapping.getInput()));
}

}
Controller: Forwards
You might be wondering what
mapping.findForward(“success”) means?
The mapping object passed to the Controller’s
perform() method is of type ActionMapping.
When you setup your struts-config.xml file you
can define forward tags that are available via the
ActionMapping.findForward() method.
In the previous example, our ActionMapping object
would have been loaded with values from the
<action-mapping> section defined for the
LogonAction controller in struts-config.xml.
<action-mappings>
<action path="/logon"
type="org.apache.struts.example.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp">
</action>
<forward name="success” path="/msgBoard.jsp"/>
<forward name=“failure” path="/msgError.jsp"/>
</action-mappings>
The View
You can begin your Struts app by creating the view in
a JSP page
Use struts taglibs for form elements
Implement logic using built in equals, present,
notPresent, and iterate tags
<%@ page language="java" %> <tr>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <th align="right">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <bean:message key="prompt.password"/>
</th>
<html:html locale="true"> <td align="left">
<head> <html:password property="password"
<title><bean:message key="logon.title"/></title> size="16" maxlength="16"/>
<html:base/> </td>
</head> </tr>
<body bgcolor="white">
<tr>
<html:errors/> <td align="right">
<html:submit property="submit"
<html:form action="/logon.do" focus="username"> value="Submit"/>
<table border="0" width="100%"> </td>
<td align="left">
<tr> <html:reset/>
<th align="right"> </td>
<bean:message key="prompt.username"/> </tr>
</th>
<td align="left"> </table>
<html:text property="username" size="16" maxlength="16"/>
</td> </html:form>
</tr>
</body>
</html:html>
Struts Strengths Simple Struts Program

Integrates well with J2EE


Open Source
Good taglib support
Works with existing web apps
Easy to retain form state
Unified error handling (via ActionError)
Easily construct processes spanning multiple steps
Clear delineation of responsibility makes long term
maintenance easier (more modular)
By
Sandeep Kumar T
CSC-India Pvt Ltd.

You might also like