0% found this document useful (0 votes)
57 views20 pages

MVC Design Pattern & Struts Framework Guide

The document discusses the Model-View-Controller (MVC) design pattern and how the Struts framework implements MVC to separate the model, view, and controller aspects of web applications. It explains how Struts uses configuration files, action forms, action beans, and JavaServer Pages (JSPs) to control the workflow and presentation of web applications based on the MVC pattern. Developing with Struts involves configuring workflow in XML files, creating action and model beans, and developing JSPs to encapsulate the different MVC components.

Uploaded by

punyaku2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views20 pages

MVC Design Pattern & Struts Framework Guide

The document discusses the Model-View-Controller (MVC) design pattern and how the Struts framework implements MVC to separate the model, view, and controller aspects of web applications. It explains how Struts uses configuration files, action forms, action beans, and JavaServer Pages (JSPs) to control the workflow and presentation of web applications based on the MVC pattern. Developing with Struts involves configuring workflow in XML files, creating action and model beans, and developing JSPs to encapsulate the different MVC components.

Uploaded by

punyaku2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CSE 135

The MVC Design Pattern &


The Struts Framework

Previous Attempts:
Model 1 Design Pattern
for every JSP page p
for every type of request r to p
insert in p code to implement the action requested by r

[Link]
If request to insert student
perform SQL INSERT
If request to delete student Messy
perform SQL UPDATE JSP!

If request to update student


perform SQL DELETE

HTML part of the JSP


[Link]
INSERT STUDENT
[Link]
UPDATE STUDENT
[Link]
DELETE STUDENT
2

1
The MVC Design Pattern:
Separating Model, View & Controller

• Development “Best
Practice”
• Known well before
web items
– Smalltalk pioneered
• Model: Access to
Underlying Databases
and Info Sources
• Controller: Control
Flow of Web App
• View: Look-and-Feel

The MVC Design Pattern

• MVC originated as Model 2 in web developers


community

• Model 1: Application logic is attached to JSPs


– Similar to previous attempts of [Link]

• Model 2: Data access and control flow decisions


in Java Beans

2
Data Entry Example – MVC Attempt

[Link] View

HTML part of the JSP


INSERT STUDENT
UPDATE STUDENT
DELETE STUDENT

Controller/Actions
Delete Update Insert
Student Student Student

Model Java classes export methods


Model
that encapsulate SQL access

DB
5

The Process and the Frictions

Business Process Owner (Client)

COMMUNICATION
Analysis/
Specification business process • Informal, imprecise
Phase and specification specification by customer
of Web application • Accompanied by hard-to-
built demos and diagrams
Chief Architect/
Technical Project Leader

COMMUNICATION
Development • Code developed may be
Phase technical specification
inconsistent with spec
and development
• Significant effort in
communicating spec formally
Developer

Problem is even worse in evolution phase when


application logic is hidden in thousands of lines of code
6

3
Struts

• Black-Box Framework Implementing MVC


– Framework: reusable “partial” application
• Struts ActionServlet provides high level control
of workflow (Part of Controller)
• You provide Beans and files to customize
framework according to your application needs
1. JSPs provide HTML presentation (View)
2. ActionForm Beans “collect” form data (Part of Controller)
3. Action Beans provide details of flow (Part of Controller)
4. [Link] declares Beans and JSPs

How To Develop Struts Applications

From 10 Miles High:


• Pass high-level control to ActionServlet
– By appropriate URL mapping in [Link]
• Design “workflow” in diagrams and then code it
in [Link]
• Develop ActionForm Beans
• Develop Action Beans
• Develop Model Beans (not part of Struts)
• Develop HTML and JSP pages

4
Struts Single Request Processing

View Request/Session
Scope
Ac1onForward Ac1onForward get
(Page or Ac1on) (Page or Ac1on) Data

set
HTTP Response HTTP Response

7 6
HTTP 5
Request 2 Ac1on ModelBean
Ini1a1ng
Page Ac1onServlet
Form
4 3
Validation Ac1onForm
Error 1
Controller
DB

Model
struts‐confi[Link]

Struts Single Request Processing (cont’d)

•1 When web app is loaded, ActionServlet parses


[Link] and associates URL paths
with Action and ActionForm Beans
– Location of [Link] is given in [Link]
• The user issues an HTTP request from an
2

initiating page P to the ActionServlet

10

5
Struts Single Request Processing (cont’d)

•3 The ActionServlet instantiates the ActionForm


Bean associated with the HTTP request URL in
[Link], and sets its properties
using the HTTP request parameters (user-
submitted data)
•4 The ActionForm Bean validates its property
values and if validation fails, ActionServlet
responds with the initiating page P displaying
appropriate error messages for the user to
correct his/her form data

11

Struts Single Request Processing (cont’d)

•5 If validation succeeds, the ActionServlet


instantiates the Action Bean associated with the
HTTP request URL in [Link], and
calls its execute method passing as parameters
the ActionForm Bean, the HTTP request and the
HTTP response objects

12

6
Struts Single Request Processing (cont’d)

•6 Within its execute method, the Action Bean


instantiates/calls Model Beans, which open a
connection to the database, execute SQL
operations, and return sets of tuples
The Action Bean places the sets of tuples in the
session so that JSP pages (View components)
can access them

13

Struts Single Request Processing (cont’d)

•7 The Action Bean returns to the ActionServlet


one of the ActionForwards with which the HTTP
request URL is associated in [Link]
An ActionForward is a possible outcome of the
Action Bean and represents either an JSP/HTML
page or another Action that will be the response
to the user’s request
Upon receiving the ActionForward, the
ActionServlet responds to the user’s request
with the corresponding JSP/HTML page or Action

14

7
Install Struts

• We will use Struts 1.3 for Phase 2 of the project


– Struts 2 will be covered later on and will not be used
for the project
• Download [Link]
• Struts is only a package containing:
\doc, \src, \lib, \apps
• Within \apps is a set of *.war files
– [Link]
– [Link]
– [Link]

15

Struts Examples

• To play with Struts examples:


– Copy [Link] under \webapps
– Access [Link]
• To play with more Struts examples:
– Copy [Link] under \webapps
– This automatically deploys a new web app directory
– Access [Link]
• To start your own Struts application:
– Copy [Link] under \webapps
– Rename \struts-blank-1.3.10 to \your_app_name

16

8
Pass Control to ActionServlet

[Link]
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>[Link]</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/[Link]</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

17

Data Entry Example - 7th Attempt


[Link] Web Appliation
Workflow
Students
(hyperlink)

success [Link]
[Link]
Insert
(buIon) Delete
StudentForm Update (buIon)
!validate InsertUpdate (buIon)

StudentForm
success !validate InsertUpdate
StudentForm
[Link]
Delete
success
[Link]
success
[Link]

18

9
Data Entry Example - 7th Attempt
[Link] Web Appliation
set
Request Scope
get Workflow
Students
(hyperlink)
StudentsRowSet

success [Link]
[Link]
Insert
(buIon) Delete
StudentForm Update (buIon)
!validate InsertUpdate (buIon)

StudentForm
success !validate InsertUpdate
StudentForm
[Link]
Delete
success
[Link]
[Link]()
(INSERT INTO Students…) success
[Link]
[Link]()
(UPDATE Students…)
[Link]()
(SELECT * FROM Students) DB [Link]()
(DELETE FROM Students…)
19

[Link] Request Processing


View Request Scope
[Link] get
StudentsRowSet

5 success set

3 4
[Link] …/[Link] Ac1onServlet ShowStudentsAc1on StudentModel
2

Controller
1
DB

struts‐confi[Link] Model

20

10
[Link] Configuration

[Link]
<struts-config>
...
<action-mappings>
<action
path="/showStudents"
type="[Link]">
<forward
name="success”
path="/pages/[Link]"/>
</action>
...
</action-mappings>
...
</struts-config>
21

[Link] Action Bean

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
...

public class ShowStudentsAction extends Action {


...

22

11
[Link] Action Bean

[Link] (cont’d)
...
public ActionForward execute(
ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws DBException {

// retrieve all students


RowSet crsStudents = [Link]();
// store the RowSet in the request scope
[Link]("crsStudents", crsStudents);

return [Link]("success");
}
}
23

[Link] Model Bean

[Link]
package [Link];
...
public class StudentModel {
private static String selectStr = ...;
private static String insertStr = ...;
private static String updateStr = ...;
private static String deleteStr = ...;

public static CachedRowSet getAllStudents() {...}


public static void insertStudent(StudentBean student) {...}
public static void updateStudent(StudentBean student) {...}
public static void deleteStudent(StudentBean student) {...}
}

24

12
[Link] ActionForward

[Link]
<%@ taglib uri="[Link] prefix="html"%>
...
<%-- -------- Iteration Code -------- --%>
<% RowSet crsStudents = (RowSet) [Link]("crsStudents");
while ([Link]()) { %>
<tr>
...
<td>
<html:text property=”middle" size="15"
value="<%=[Link](\”middleName\")%>" />
</td>
...
</tr>
<% } %>
...

25

[Link] Request Processing


View
[Link]
(Step 2 on Slide 8)

7 success

2 5
6
…/[Link] InsertStudentAc1on StudentModel
[Link] Ac1onServlet
Form Valida1on
Error 4 StudentFormInsertUpdate

1 3
Controller DB

struts‐confi[Link] Model

26

13
[Link] Configuration

[Link]
...
<form-bean name="studentFormInsertUpdate”
type="[Link]"/>
...
<action
path="/insertStudent”
type="[Link]"
validate="true”
scope="request"
Not what you
think it is!
input="/[Link]”
name="studentFormInsertUpdate">
<forward name="success" path="/[Link]”
redirect="true"/>
</action>
27

[Link] ActionForm Bean

[Link]

package [Link];
...
public class StudentFormInsertUpdate extends ActionForm {

private String id = null;


private String first = null;
private String middle = null;
private String last = null;

public String getId() { return id; }


public void setId(String id) { [Link] = id; }
...

28

14
[Link] ActionForm Bean

[Link] (cont’d)

...
/**
* Reset all properties to their default values.
*/
public void reset(ActionMapping mapping,
HttpServletRequest request) {
setId(null);
setFirst(null);
setMiddle(null);
setLast(null);
}
...

29

[Link] ActionForm Bean

[Link] (cont’d)
...
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if ((id == null) || ([Link]() < 1))


[Link]("idMsgTag1",
new ActionMessage("[Link]", ”ID"));
...

return errors;
}
}
30

15
[Link] Action Bean

[Link]
public class InsertStudentAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws DBException {

// cast the form


StudentFormInsertUpdate iForm =
(StudentFormInsertUpdate) form;
// insert the student
[Link](iForm);

return [Link]("success");
}
}
31

[Link] ActionForward

[Link]
<%@ taglib uri="[Link] prefix="html"%>
...
The corresponding
<!-- in case form validation fails --> Ac1onForm bean
<html:errors /> will also be used to
... populate HTML form
<tr>
<html:form action="/insertStudent">
<td><html:text property="id" size="10" /></td>
<td><html:text property="first" size="15" /></td>
<td><html:text property="middle" size="15" /></td>
<td><html:text property="last" size="15" /></td>
<td><html:submit value="Insert" /></td>
<td><html:reset /></td>
</html:form>
</tr>
...

32

16
[Link] Structure

<struts-config>
<!-- ========================= Form Bean Definitions -->
<form-beans>...</form-beans>

<!-- ================== Global Exception Definitions -->


<global-exceptions>...</global-exceptions>

<!-- ==================== Global Forward Definitions -->


<global-forwards>...</global-forwards>

<!-- ==================== Action Mapping Definitions -->


<action-mappings>...</action-mappings>

<!-- ================= Message Resources Definitions -->


<message-resources parameter="MessageResources" />
</struts-config>
33

Global Exceptions

[Link]

<!-- ==================== Global Exception Definitions -->


<global-exceptions>
<exception key="[Link]"
type="[Link]"
path="/pages/[Link]"/>
</global-exceptions>

34

17
Global Exceptions

[Link]

package [Link];

public class DBException extends Exception {

public DBException() {
super();
}

public DBException(String message) {


super(message);
}
}

35

Global Exceptions

[Link]

public static void insertStudent(


StudentFormInsertUpdate student) throws DBException {

try {
...
} catch (SQLException ex) {
throw new DBException(ex);
} catch (NamingException ex) {
throw new DBException(ex);
}
}

36

18
Global Exceptions

[Link]

public class InsertStudentAction extends Action {


public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws DBException {

...
[Link](...);
...
}
}

37

Global Exceptions

[Link]

<%@ taglib uri="[Link] prefix="html"%>

<html>
<body>
<h2>Database Exception</h2>
...
<h3>Here is the message generated by the thrown database
exception:</h3>

<p><html:errors /></p>

</body>
</html>

38

19
Global Forwards

[Link]

<!-- ====================== Global Forward Definitions -->


<global-forwards>
<forward name="showStudents" path="/[Link]"/>
</global-forwards>

[Link]

<%@ taglib uri="[Link] prefix="html"%>


<b>Data Entry Menu</b>
<ul>
<li><html:link forward="showStudents">Students</html:link></li>
...
</ul>

39

Message Resources

[Link]

# -- app --
[Link]=Struts Data Entry Application
...

[Link]

<%@ taglib uri="[Link] prefix="bean"%>


<html>
<head>
<title><bean:message key="[Link]" /></title>
</head>
...
</html>

40

20

You might also like