You are on page 1of 53

Chapter 12

Architecting
JSP[tm]/Servlet Application

© 2002, Sun Microsystems, Inc. All rights reserved.


Objectives

• Examine several architectural modules for


developing web application:
– Building applications with JSP[TM] alone.
– Combing servlets and JSP pages.
– Understanding architectural tradeoffs.
• A case study:
– A portal for composing exam questions and
displaying exams.
– Choosing the appropriate architecture for the
case study.
• Lab exercise:
– Work on the architectural design.
MVC Pattern
Three Logical Layors in Web
Application
• Presentation layer (View)
– Display elements, such as HTML, XML, or Java Applets.
– Get input from the end user and display the application's
results.
– Not concern with how the information was obtained, or
from where.
• Application layer (Model)
– Models the data and behavior behind the business process.
– Responsible for actually doing:
• e.g. Performing queries against a DB, calculating the
business process, or processing orders.
– Encapsulate of data and behavior which is independent of
its presentation.
Three Logical Layors in Web
Application (Cont.)
• Control layer (Control)
– Determines the applications flow.
– Serves as the logical connection between the
user's interaction and the business services on
the back.
– Responsible for making decisions among multiple
presentations.
• e.g. User's language, locale or access level
dictates a different presentation.
– A request enters the application through the
control layer, it will decide how the request
should be handled and what information should
be returned.
Web Applications

• It is often advantageous to treat each tier as an


independent portion of your application.
• Don not confuse logical separation of
responsibilities with actual separation of
components.
• Some of the tiers can be combined into single
components to reduce application complexity.
• Architectural approaches:
– Page-centric design (Only JSPs)
– Servlet-centric design (Servlets and JSPs)
– Enterprise JavaBeans[TM] design (Servlets, JSP
and EJB)
• EJB code camp will cover this in more detail.
Page-centric Diagram
Page-centric Technology

• Page-centric approach is composed of a series of


interrelated JSP pages:
– handles all aspects of the application - the
presentation, control, and the application logic.
• The application logic and control decisions
– hard coded into its page.
– Expressed through its Beans, scriptlets, and
expression at run time.
• Next page visit will be determined by
– A user clicking on a hyper link, e.g. <A
HREF="find.jsp">
– Through the action of submitting a form, e.g.
<FORM ACTION="search.jsp">
Page-centric Example

memu.jsp catalog.jsp checkout.jsp

dataBase

page–centric catalog application


Page-centric: Simple Steps
Application

• One page might display a menu of options, anther


might provide a form for selecting items from the
catalog,and another would be to complete shopping
process.
– This doesn't mean we lose separation of
presentation and content.
– Still use the dynamic nature of JSP and its
support for JavaBeans component to factor out
business logic from presentation.
– The pages are tightly coupled:
• Need to sync up request parameters
• Be aware of each other's URLs.
Page-centric: Component Page
Diagram

header.jsp Item details

Commodore 1541
Capacity180k
details.jsp Cost: 200
Aligened: sometimes

[main][logoff]
footer.jsp

Component design
Page-centric: Component Page

• Create headers, footers and navigation bars


in JSP pages and place them in JSPs.
– Provides better flexibility and reusability.
– Easy to maintain.
• <%@ include file = "header.jsp" %>
– Use it when the file (included) changes
rarely.
– Faster than jsp:include.
• <jsp:include page="header.jsp" flush="true">
– Use it for content that changes often
– if which page to include can not be decided
until the main page is requested.
Servlet-centric MVC Diagram

Redirect
Servlet-centric Technology

• Use JSPs only for presentation, with the control


and application logic handled by a servlet or
servlets.
• Servlet is served as a gatekeeper:
– Provides common services, such as
authentication, authorization, login, error
handling, and etc.
• Servlet is also acting as a re-direct:
– Being the central controller.
– Act as a state machine or an event dispatcher to
decide upon the appropriate logic to handle the
request.
• One master Servlet, one servlet per use case or business
function, or a balance of two depends on the granularity
and the meaningfulness within your application.
Flow Control: Dispathcing Requests

• How to control the flow?


String url="relativeURL";
RequestDispatcher dispatch =
request.getRequestDispatcher(url);
//OR
String url="abosluteURL"
RequestDispatcher dispatch =
getServletContext().getRequestDispatcher(url);

• Use forward or include methods:


– Call forward to completely transfer
control to destination page.
– Call include to insert output of
destination page and then continue on.
Storing Data in Request

• Store data that servlet looked up and


that JSP will use in this request.
• Sevlet: store data.
BeanClass value = new BeanClass(..);
request.setAtrribute("bean", value);

• JSP: retrieve data.


<jsp:useBean
id = "bean"
class="BeanClass"
scope="request" />
Storing Data in Session

• Store data that servlet looked up and


that JSP will use in this request and in
later requests from the same client.
• Sevlet: store data.
BeanClass value = new BeanClass(..);
HttpSession
session=request.getSession(true);
session.setAttribute("bean", value);
• JSP: retrieve data.
<jsp:useBean
id = "bean"
class="BeanClass"
scope="session" />
Storing Data in Servlet Context

• Store data that servlet looked up and


that JSP will use in this request and in
later requests from the any client.
• Sevlet: store data.
BeanClass value = mew BeanClass(..);
getServletContext()
.setAttribute("bean, value);

• JSP: retrieve data.


<jsp:useBean
id = "bean"
class="BeanClass"
scope="application" />
Handle Different Action

• How to handle different actions?


– Use command pattern:
• The servlet dispatches the request to the
particular object associated with performing
that command.
• The servlet merely mediates the request
between the JSP and the command object.
if (cmd.equals("save")) {
doSave();
}
if (cmd.equals("edit")) {
doEdit();
}
if (cmd.equals("remove")) {
doRemove();
}
Trade-offs
• Page-centric approach:
– Tends to be the most intuitive to web
developers and designers.
– More straightforward than the other approaches.
– May encourage spaghetti JSP pages.
• Business logic may get lost in the display
pages-- should leave it in domain object.
– JSPs are harder to debug than straight Java
code:
• Result in a failed compilation and a long list of
useless compiler errors referring to the auto-
generated code.
• By relying on them to handle requests, it is all
or nothing.
Trade-offs (Cont.)

• Servlet-centric approach:
– Loosens the coupling between the pages and
improves the abstraction between presentation
and application logic.
• Reduces JSPs for pure data display and input
collection activities.
• Eliminate for embedding presentation
information inside the servlets.
• Most of the business logic can be debugged
through the servlet before passed to
JavaBeans and JSP.
– If the flow logic that is hard-coded in the
Servlets changes often, the advantage can be
perceived than actual.
Best Practice

• Factor out the business logic into


business objects and complex display
logic into view objects.
– Improves reusability, maintainability, unit
testing and regression testing.
How Do I Decide?

• Only you can decide what's best for your project.


• Use page-centric
– If the application is simple enough that links
from page to page.
• Use servlet-centric
– Each link or button click requires a great deal of
processing and decision-making about what
should be displayed next.
• Mapping between requests and responses can help
– Each request maps to one and only one response
• No need for controller.
– Each request spawns a great deal of logic and a
variety of different views can result
• A servlet is ideal.
Page-centric Example

View
search.html
Request 1

response list.jsp
Client
Model
response

forward

JavaBeans
Request 2
Controller
find.jsp
Request 3
redirect

delete.jsp
Servlet-centric Example

View
search.html
Request 1

response list.jsp
Client
Model
response

forward

JavaBeans
Request 2
Controller

Request 3
servlet
Servlet/JSP/EJB Example

View

search.html Model
Request 1

response list.jsp
Client

response JavaBeans Entity EJBs


forward

Request 2

Request 3
servlet
Session EJBs

Controller
EJB

• The previous two approaches do not directly support


complicated transaction management and distributed
architectures.
• Enterprise JavaBeans(EJBs)
– EJBs are reusable business logic components for use in
distributed, multiplier application architectures.
• JavaBenas vs. EJBs
– Not much in common (taking advantage of reusable
components is the same).
– EJBs flow a completely different set of conventions and
interfaces.
– EJBs are not accessible directly through Bean containers or
JSP tags.
– EJBs run in an EJB container such as an application server.
Case Study: A Portal for Exams

• Application Requirement:
– This portal should be an on-line application.
• The portal should allow lectures and students
into different application.
– A lecture should be able to compose, delete,
view and organize the exam questions .
• An exam is made up of multiple questions.
• Each question should consist 2 parts the
question and the answer.
• Different type of questions can be specified,
i.e. Multiple choice, short answer question and
so on.
• Exam questions can be stored into persistent
data.
Case Study: A Portal for Exams
(Cont.)

• Application requirement:
– A student should be able to display the
question and answer the questions in the
exam.
• Exam questions could be displayed one at a
time.
• A student should be able to go back and forth
through the exam questions.
• The answer of each question can be stored
into persistent data.
Application Modules

• Lectures:
– Compose/Delete/View exam questions.
• Students
– Display/Write Exams.
Choose Appropriate Design

• Could not just use JSP only


– Business logic and control is too complex
for using JSP pages only design.
• Servlet-centric approach is more
appropriate to use in this application.
– Need flow control.
– Need to make complex logical decision.
Lectures Module Design

index.jsp memu.jsp

create_exam.jsp

ProcessQuestionServlet
question_entry .jsp
CREATE_EX

ADD_TO_EXAM_FROM_REPOSITOR
question.jsp

exam
ADD
list_question.jsp DISCARD }
Question ADD_ANSWER
body.jsp
body.jsp
SAVE
Question body
Log_OUT
question_repository.jsp
JavaBeans Controller
Index Page: index.jsp
Create or Dispaly: menu.jsp
Create Exams: create_exam.jsp
Define Contants
public interface Constants {
// Servlet init params
public static final String SAVE_DIRECTORY = "saveDirectory";
public static final String QUESTION_TYPE = "questionType";
public static final String QUESTION_TYPE_TEXT =
"questionTypeText";
// ACTIONS from froms
public static final String ACTION = "action";
public static final String ADD = "add";
public static final String SAVE = "save";
public static final String CREATE_EXAM = "create_exam";
public static final String LOGIN = "login";
public static final String LOGOUT = "logout";
public static final String ADD_ANSWER = "add_answer";
...
// Parameters in a form
public static final String ANSWER_TYPE = "answer_type";
public static final String RADIO_ITEM = "radio_item";
public static final String TEXTBOX_ITEM = "textbox_item";
public static final String LECTURER = "lecturer";
public static final String STUDENT = "student";
// Servlet and JSP pages
public static final String INDEX_PAGE = "index.jsp";
public static final String PROCESS_QUESTION_SERVLET =
"process_question";
...
}
JSP: create_exam.jsp
<%@page import="java.util.*, tinc.servlet.*, tinc.core.*"
%>
<html>
<head>
<title>Login</title>
<meta http-equiv="expires" content="0">
<meta http-equiv="pragma" content="no-cache">
</head>
<body>
<%@include file="time.jsp" %>
<form method="POST" action="process_question">
<b>Subject: </b><input type="text" name="subject"
size="65">
<b>Duration: </b><input type="text" name="duration"
value="120" size="5">mins
<hr>
<input type="submit" name="action" value=<%=
Constants.CREATE_EXAM %>>
<input type="submit" name="action" value=<%=
Constants.LOGOUT %>>
<input type="reset" name="action" value="clear">
</form>
</body></html>
WEB.XML
<servlet>
<servlet-name>processQuestion</servlet-name>
<servlet-class>
tinc.servlet.ProcessQuestionServlet
</servlet-class>
...

<init-param>
<param-name>questionTypeText</param-name>
<param-value>
Multiple choice (radio/checkbox):Short answer entry
</param-value>
</init-param>
...
</servlet>
<servlet-mapping>
<servlet-name> processQuestion </servlet-name>
<url-pattern> /process_question </url-pattern>
</servlet-mapping>
ProcessQuestionServlet
public void doPost(HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException {
String action = req.getParameter(Constants.ACTION);
String jumpTo = Constants.QUESTION_BODY_PAGE;
if (action.intern() == Constants.ADD) {
doAdd(req, sess);
} else if (action.intern() == Constants.ADD_ANSWER) {
doAddAnswer(req, sess); ...
jumpTo = Constants.QUESTION_ENTRY_PAGE;
} else if (action.intern() == Constants.CREATE_EXAM) {
doCreateExam(req, sess);
jumpTo = Constants.QUESTION_ENTRY_PAGE;
} else if (action.intern() == Constants.SAVE) {
doSaveExam(sess);
jumpTo = Constants.MENU_PAGE;
} else if (action.intern() ==
Constants.ADD_TO_EXAM_FROM_REPOSITORY) {
doAddToExamFromRepository(req, sess);
jumpTo = Constants.QUESTION_ENTRY_PAGE;
} else if (action.intern() == Constants.DISCARD) {
sess.removeAttribute(Constants.CURRENT_QUESTION);
jumpTo = Constants.QUESTION_ENTRY_PAGE;
} else if (action.intern() == Constants.LOGOUT) {
sess.invalidate();
jumpTo = "/" + Constants.INDEX_PAGE; }
RequestDispatcher rd = req.getRequestDispatcher(jumpTo);
rd.forward(req, res); }}
Question Entry: question_entry.jsp
Compose Questions: question.jsp
Compose Mutiple-Choice Questions
Compose Short Questions
Create Different Type of
Questions

Body item

Radio body item Text body item

• RadioBodyItem and TextBodyItem both are


JavaBeans component.
• They both implement interface BodyItem.
– Can add more question types later on.
Server Objects

• JavaBeans component:
– Qeustion, QuesionBody, and Exam.
• Exam question are described in Question.
• Each question has two parts: question header is
in Question, and question body is contained in
QuesionBody.
– The body contains possible answers which
describe in BodyItem.
– RadioBodyItem and TextBodyItem handle
different question type and the associated
answer.
• Exam contains information such as exam
duration, subject, and a collection of questions.
List Questions: list_question.jsp
JSP: list_questions.jsp
<%@page info="List question" import="java.util.*,
tinc.servlet.*, tinc.core.*" %>
<jsp:useBean id="current_exam" class="tinc.core.Exam"
scope="session" />
<%! Question[] question; %>
...
<jsp:getProperty name="current_exam" property="subject" />
</h1>
...
<jsp:getProperty name="current_exam" property="duration" />
mins</h1>
<hr>
<% question = current_exam.getQuestions();
if (question.length == 0) {
%>
...
<%= question[i].getQuestionText() %></font>
<% } %>
</ol>
<% } %>
<br>
<h1><a href="question_entry.jsp">Back to questions
entry</a></h1>
JavaBeans Component: Exam

public class Exam implements Serializable {


private final String subject;
private int duration;
private HashMap questions;
...
public Exam() {
subject = "Not set";
year = 2001;
duration = 120;
questions = new HashMap();
}
public int getDuration() {
return (duration);
}
public void setDuration(int d) {
duration = d;
}
...
}
Add Questions From Repository:
question_repository.jsp

question_repository.jsp
Student Module Design

index.jsp

exam.jsp

memu.jsp

Question JavaBeans
doExamServlet

Start
CurrentQuestionNumber
Iterate
Next
Previous

Logout/complete
?page # = number

Controller
Sit for a Exam
Exam.jsp
DoExamServlet
public class DoExamServletextends HttpServlet {
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String jumpTo = Constants.EXAM_PAGE;
String action = req.getParameter(Constants.ACTION);

if ((action == null) || (action.intern() ==


Constants.START)) {
doStart(req, sess);
jumpTo = jumpTo + "?" + Constants.CURRENT_QUESTION_NUMBER +
"=1";
} else if (action.intern() == Constants.NEXT) {
jumpTo = jumpTo + "?" + Constants.CURRENT_QUESTION_NUMBER +
"=" + n;
} else if (action.intern() == Constants.PREVIOUS) {
jumpTo = jumpTo + "?" + Constants.CURRENT_QUESTION_NUMBER +
"=" + p;
} else if ((action.intern() == Constants.COMPLETE)
|| (action.intern() == Constants.LOGOUT)) {
sess.invalidate();
...
return;
}

RequestDispatcher rd = req.getRequestDispatcher(jumpTo);
rd.forward(req, res); } }
Summary

• Examined several architectural modules for


developing web application:
– Building applications with JSP[TM] alone.
– Combing servlets and JSP pages.
– Discussed the trade off of using JSP or
servlets.
• Demonstrated a exam portal case study:
– From design to implementation.
• Only you can decide what's best for your
project.

You might also like