Object Oriented Concepts and Programming - Ii (Advance Java)
Object Oriented Concepts and Programming - Ii (Advance Java)
BLOCK 4:
SERVLETS & JSP
PROGRAMMING
- Dr. B. R. Ambedkar
Author
Prof. Rekharani Mathur
Language Editor
Mr. Vipul Shelke
Acknowledgment
Every attempt has been made to trace the copyright holders of material reproduced
in this book. Should an infringement have occurred, we apologize for the same and
will be pleased to make necessary correction/amendment in future edition of this
book.
The content is developed by taking reference of online and print publications that
are mentioned in Bibliography. The content developed represents the breadth of
research excellence in this multidisciplinary academic field. Some of the
information, illustrations and examples are taken "as is" and as available in the
references mentioned in Bibliography for academic purpose and better
understanding by learner.'
ROLE OF SELF INSTRUCTIONAL MATERIAL IN DISTANCE LEARNING
BLOCK 2: JDBC
UNIT 1 NETWORKING
Introduction, Networking Protocols, Differences between TCP and
UDP, Networking Classes In JDK, Sockets and Port numbers in
Networking, Creating Client and Server Program through Sockets,
Running Client Server Programs
UNIT 2 JDBC (JAVA DATABASE CONNECTIVITY)
Introduction, Steps to write a JDBC Program, Establishing a
Connection, Creating JDBC Statements, Retrieving Values from Result
Sets, Using Prepared Statements, Calling a Stored Procedure from
JDBC
BLOCK 3: RMI & JAVABEANS
UNIT 1 SERVLETS
Introduction, Architecture of the Servlet Package, Interacting with
Clients, Threading Issues, Saving Client State, Request Dispatcher,
Compiling and Running Servlets in Apache Tomcat 4.0
UNIT 2 INTRODUCTION TO STRUTS
Introduction, Struts Controller Components , Struts Action Classes,
Struts Model Components, The Struts View Components, Configuring
the Struts Application, Configuring the web.xml file for Struts
UNIT 3 JSP (Java Server Pages)
Introduction, Comparing JSP with ASP, JSP Architecture, JSP Syntax
Basics, JSP Implicit Objects, Standard Actions, JSP Tag Libraries
Dr. Babasaheb BCA - 401
Ambedkar
Open University
UNIT 1
SERVLETS 02
UNIT 2
INTRODUCTION TO STRUTS 15
UNIT 3
JSP (JAVA SERVER PAGES) 32
BLOCK 4: SERVLETS AND JSP
PROGRAMMING
Block Introduction
Struts is an application development framework that is designed for and
used with the popular J2EE (Java 2, Enterprise Edition) platform. JSP is a server
side technology which helps to create a webpage dynamically using java as the
programming language.
In this block, we will detail about the basic concept of Architecture of the
Servlet Package. The block will focus on the study and concept of various issues
that appears at the time of threading. The students will give an idea on Struts
Controller Components and its characteristics features.
In this block, the student will made to learn and understand about the basic
of about configuring web.xml file for Struts. The concept related to Struts Action
Classes and Model Components will also be explained to the students. The student
will be demonstrated practically about running Servlets in Apache Tomcat 4.0.
Block Objective
After learning this block, you will be able to understand:
Block Structure
Unit 1: Servlets
Unit 2: Introduction to Struts
Unit 3: JSP (Java Server Pages)
1
Servlets and JSP UNIT 1: SERVLETS
Programming
Unit Structure
1.0 Learning Objectives
1.1 Introduction
1.2 Architecture of the Servlet Package
1.11 Assignment
1.12 Activities
Threading Issues
1.1 Introduction
Servlets are modules of Java code that run in a server application (hence the
name "Servlets", similar to "Applets" on the client side) to answer client requests.
Servlets are not tied to a specific client-server protocol but they are most
2
commonly used with HTTP and the word "Servlet" is often used in the meaning of Servlets
"HTTP Servlet".
Servlets make use of the Java standard extension classes in the packages
javax.servlet (the basic Servlet framework) and javax.servlet.http (extensions of
the Servlet framework for Servlets that answer HTTP requests). Since Servlets are
written in the highly portable Java language and follow a standard framework,
they provide a means to create sophisticated server extensions in a server and
operating system independent way.
When the Servlet needs to be unloaded (e.g. because a new version should
be loaded or the server is shutting down) the destroy() method is called. There
may still be threads that execute the service method when destroy is called, so
3
Servlets and JSP destroy has to be thread-safe. All resources which were allocated in init should be
Programming released in destroy. This method is guaranteed to be called only once during the
Servlet's lifecycle.
c. Both a and b
d. Neither a nor b
The methods to which the service method delegates HTTP requests include:
4
By default, these methods return a BAD_REQUEST (400) error. Your
servlet should override the method or methods designed to handle the HTTP
interactions that it supports. This section shows you how to implement methods
that handle the most common HTTP requests: GET and POST.
The HttpServlet's service method also calls the doOptions method when the
servlet receives an OPTIONS request, and doTrace when the servlet receives a
TRACE request. The default implementation of doOptions automatically
determines what HTTP options are supported and returns that information. The
default implementation of doTrace causes a response with a message containing
all of the headers sent in the trace request. These methods are not typically
overridden. HTTP servlets are typically capable of serving multiple clients
concurrently. If the methods in your servlet that do work for clients that access a
shared resource, then you must either be synchronize access to resource or create
servlet which handles only one client request at a time
d. D. Neither a nor b.
When we say that a program is multithreaded, we are not implying that the
program runs two separate instances simultaneously. Rather, we are saying that
the same instance spawns multiple threads that process this single instance of
code. This means that more than one sequential flow of control runs through the
same memory block.
5
Servlets and JSP When multiple threads execute a single instance of a program and therefore share
Programming memory, multiple threads could possibly be attempting to read and write to the
same place in memory. In fig 1.2 we see a multithreaded program where multiple
threads processing are done at same time.
6
Check your progress 3
1. Each thread is a sequential flow of:
a. data
b. control
c. information
d. all of above
Session Tracking:
It is the mechanism that servlets use to maintain state about a series of
requests from the same user across some period of time. Sessions are shared
among the servlets accessed by a client. This is convenient for applications made
up of multiple servlets. To use session tracking,
Cookies:
It is also a mechanism that a servlet uses to have clients hold a small amount
of state-information associated with the user. Cookies serve as a facility for
servers to send information to a client. This information is then housed on the
client, from which the server can later retrieve the information. Servlets can use
the information in a cookie as the user enters a site (as a low-security user sign-on,
for example), as the user navigates around a site (as a repository of user
preferences for example), or both.
7
Servlets and JSP
Programming
In this we see that server can send many cookies to the client where every
cookie is sent as different response header. It is also true for client talking back to
the server, except that there, we are dealing with multiple request headers. It is
important to note that you can have cookies with the same name.
Each HTTP request and response header is named and has a single value.
For example, a cookie could be a header named BookToBuy with a value
304qty1, indicating to the calling application that the user wants to buy one copy
of the book with stock number 304.
Multiple cookies can have the same name. For example, a servlet could send
two cookies with headers named BookToBuy; one could have the value shown
previously, 304qty1, while the other could have a value 301qty3. These cookies
would indicate that the user wants to buy one copy of the book with stock number
304, and three copies of the book with stock number 301.
In addition to a name and a value, you can also provide optional attributes
such as comments. Current web browsers do not always treat the optional
attributes correctly, so you should not rely on them.
b. data application
c. windows application
d. none of above
8
1.6 Request Dispatcher
RequestDispatcher is an interface, implementation of which defines an
object which can dispatch request to any resources(such as HTML, Image, JSP,
Servlet) on the server. The RequestDispatcher interface provides the facility of
dispatching the request to another resource it may be html, servlet or jsp. This
interface can also be used to include the content of another resource also. It is one
of the way of servlet collaboration. There are two methods defined in the
RequestDispatcher interface.
9
Servlets and JSP
Check your progress 5
Programming
1. A three digit error codes shows error in requesting from client is:
a. Codes starting from 200
10
Fig 1.7 creating directory
Creating a Servlet
There are three different ways to create a servlet.
When a request comes in for the servlet, the Web Container calls the
servlet's service() method and depending on the type of request the service()
method calls either the doGet() or doPost() method.
Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require
different JAR files. In Apache Tomcat server servlet-api.jar file is required to
compile a servlet class. Steps to compile a Servlet
11
Servlets and JSP
Programming
If you are starting Tomcat Server for the first time you need to set
JAVA_HOME in the Enviroment variable. The following steps will show you
how to set it.
Click on New button, and enter JAVA_HOME inside Variable name text
field and path of JDK inside Variable value text field. Click OK to save.
b. Google Tomcat
c. Server tomcat
d. none of these
An HTTP Servlet handles client requests through its service method. The
service method supports standard HTTP client requests by dispatching each
request to a method designed to handle that request.
A thread is many times called an execution context or a lightweight process
which is single sequential flow of control within a program. When you run one of
these sorting applets, it creates a thread that performs the sort operation.
Cookies serve as a facility for servers to send information to a client. This
information is then housed on the client, from which the server can later retrieve
the information.
Answers: (1-a)
Answers: (1-c)
13
Servlets and JSP Check your progress 3
Programming
Answers: (1-c)
Answers: (1-a)
Answers: (1-c)
Answers: (1-a)
1.10 Glossary
1. Activation - The process of transferring an enterprise bean from secondary
storage to memory.
2. Host - A computer that is connected to a network and that provides an
access point to that network.
1.11 Assignment
Explain Architecture of the Servlet Package?
1.12 Activities
Study about Saving Client State.
14
UNIT 2: INTRODUCTION TO STRUTS
Unit Structure
2.0 Learning Objectives
2.1 Introduction
2.2 Struts Controller Components
2.11 Assignment
2.12 Activities
2.1 Introduction
Struts is an application development framework that is designed for and
used with the popular J2EE (Java 2, Enterprise Edition) platform. It cuts time out
of the development process and makes developers more productive by providing
15
Servlets and JSP them a series of tools and components to build applications with. It is non-
Programming proprietary and works with virtually any J2EE-compliant application server. Struts
falls under the Jakarta subproject of the Apache Software Foundation and comes
with an Open Source license (meaning it has no cost and its users have free access
to all its internal source code).
16
Introduction to
Struts
In the above figure we see that when user sends a query with a browser, then
the controller(servlet) gets and processes such query and decides which action will
be called or which view component this query should be forward. Once the
controller calls an action, action can read data from database and shows data to the
model component, java beans. The action returns next step to controller which
further will check what kind is the next step. (JSP View, next action, …) and
forwards to it.
The view component (JSP) reads the updated data from the model
component and prepare this for the presentation. Then it sends the answer as
HTML site back to the browser. The user sees the result of his query.
b. Frameworks
c. Java Development Tool Kit
d. Language.
17
Servlets and JSP 2.3 Struts Action Classes
Programming
It is seen that actions are the main part of Struts2 framework since they are
for any Model View Controller structure. Every URL is mapped to particular
action that shows processing logic required to service request from user. In this,
action also serves in two capacities:
The only need for actions in Struts2 is that there must be single no-argument
method which will able to return a String or Result object that and must be POJO.
If the no-argument method is not specified, the default behavior is to use the
execute() method. Optionally you can extend the ActionSupport class which
implements six interfaces including Action interface. The Action interface is as
follows:
In the action method shown below with Hello World, we see that:
18
To explain point used by action method to controls the view, the following
amendments are made to carry out method and extend the class ActionSupport as
follows:
19
Servlets and JSP
Programming
Here we see that there appears some logic in execute method which is the
name attribute that equals to string SECRET what we return SUCCESS as output,
and if not, then it will return ERROR.
d. all of above
21
Servlets and JSP Strut implements the Model-View-Controller (MVC) design pattern.
Programming
It is noted that MVC implement by action, result and Filter Dispatcher. Here
the controller’s work is to map user request to required action which is done by
Filter Dispatcher. It includes data and business logic and model is worked out
using action component. The presentation component of the MVC pattern is view
and view is implemented using JSP, Velocity Template, Freemaker or some other
presentation-layer technology. - See more at: http://www.j2eebrain.com/java-
J2ee-struts-framework.html#sthash.2napVEkU.dpuf
a. StrutsTypeConverter
b. StringTypeConverter
22
2.5 The Struts View Components
We see that view is responsible for rendering state of model. In this, the
presentation semantics are summarize inside the view, as a result of which the
model data can be adapted for various different kinds of clients. The view
modifies itself when change in model is communicated to view. A view forwards
user input to the controller. The view is simply as JSP or HTML file. There is no
flow logic, no business logic, and no model information -- just tags. Tags are one
of the things that make Struts unique compared to other frameworks like Velocity.
The view components typically employed in a Struts application are:
HTML
Struts ActionForms
JavaServer Pages
Custom tags
Struts ActionForm
Struts ActionForm objects are applied in structure so as to pass client input
data back and forth among user and business layer. The structure directly will
collect the input from request and pass it to Action with the help of form bean,
further which pass on to business layer. To keep the presentation layer decoupled
from the business layer, you should not pass the ActionForm itself to the business
layer; rather, create the appropriate DTO using the data from the ActionForm. The
following steps illustrate how the framework processes an ActionForm for every
request:
23
Servlets and JSP
Check your progress 4
Programming
1. The function of Struts ActionForm objects is to:
a. pass clients input data to user
b. pass clients input data back and forth among user and business layer
c. pass clients input data back and forth among business layer
d. none of above
24
Fig 2.4 setting application
The IDE creates the project folder in your file system. As with any web
application in the IDE, the project folder contains all of your sources and the
IDE's project metadata, such as the Ant build script. However, your web
application in addition has all Struts libraries on classpath. Not only are they on
the application's classpath, but they are included in the project and will be
packaged with it later when you build the project. The project opens in the IDE.
The Projects window is the main entry point to your project sources. It shows a
logical view of important project contents.
25
Servlets and JSP
Programming
26
Check your progress 5
1. Struts libraries are available in :
a. datapath
b. classpath
c. applicationpath
d. none of above
27
Servlets and JSP 2.7 Configuring the web.xml file for Struts
Programming
The web.xml configuration file is a J2EE configuration file that determines
how elements of the HTTP request are processed by the servlet container. It is not
strictly a Struts2 configuration file, but it is a file that needs to be configured for
Struts2 to work.
The web.xml web application descriptor file represents the core of the Java
web application, so it is appropriate that it is also part of the core of the Struts
framework. In the web.xml file, Struts defines its FilterDispatcher, the Servlet
Filter class that initializes the Struts framework and handles all requests. This
filter can contain initialization parameters that affect what, if any, additional
configuration files are loaded and how the framework should behave.
The struts.xml file contains the configuration information that you will be
modifying as actions are developed. This file can be used to override default
settings for an application, for example struts.devMode = false and other settings
which are defined in property file. This file can be created under the folder WEB-
28
INF/classes. Let us have a look at the struts.xml file we created in the Hello World
example explained in previous chapter.
Here we see that the DOCTYPE, has all struts configuration file required to
have correct doctype. The <struts> is root tag element, where we declare various
packages with <package> tags. The <package> allows separation and
modularization of the configuration. This is very useful when you have a large
project and project is divided into different modules.
d. none of above
29
Servlets and JSP 2.8 Let Us Sum Up
Programming
While studying this unit, we have learnt that Struts is an application
development framework that is designed for and used with the popular J2EE (Java
2, Enterprise Edition) platform.
The controller is responsible for intercepting and translating user input into
actions to be performed by the model.
Answers: (1-b)
Answers: (1-d)
Answers: (1-a)
Answers: (1-b)
Answers: (1-b)
30
Check your progress 6
Answers: (1-a)
2.10 Glossary
1. Code - A number that uniquely identifies a catalog entry in the WebSphere
Commerce system.
2. Data bean - A type of bean that is placed in a JSP file.
2.11 Assignment
Write short note on Struts Action Classes.
2.12 Activities
Collect some information on cconfiguring web.xml file for Struts.
31
Servlets and JSP UNIT 3: JSP (JAVA SERVER PAGES)
Programming
Unit Structure
3.0 Learning Objectives
3.1 Introduction
3.2 Comparing JSP with ASP
3.11 Assignment
3.12 Activities
JSP Architecture
3.1 Introduction
JSP is a server side technology which helps to create a webpage
dynamically using java as the programming language. JSP is a specification from
Sun Microsystems. It is an extension to Servlet API. It controls content or
32
appearance of Web pages through application of servlets, which are small JSP (Java Server
programs that are specified in Web page and run on Web server to alter Web page Pages)
JSP pages are interpreted or compiled ASP code are interpreted on fly each
in servlet time it gets accessed
JSP pages actually takes longer time to ASP pages takes shorter time to load
load
JSP pages works faster after loading ASP pages does not work faster after
loading
As of today, most web developers are using either JSP or the improved
version of ASP called ASP.NET. For people who are using a web server that’s
running Microsoft Windows, using ASP or ASP.NET is already a given. Those
who use open source software like Linux can choose between a few options that
are either free or not. Most people use other open source software like PHP while
JSP stands a distant second.
33
Servlets and JSP
Check your progress 1
Programming
1. JSP is:
a. software
b. data
c. client
d. windows
Model1 Architecture
Model2 Architecture
Model1 Architecture:
In this Model, JSP plays a key role and it is responsible for of processing the
request made by client. Client (Web browser) makes a request, JSP then creates a
bean object which then fulfills the request and pass the response to JSP. JSP then
sends the response back to client. Unlike Model2 architecture in this Model, most
of the processing is done by JSP itself.
34
Model 2 Architecture:
In this Model Servlet plays a major role and it is responsible for processing
the client’s(web browser) request. Presentation part (GUI part) will be handled by
JSP and it performs this with the help of bean as shown in below figure. The
servlet acts as controller and in charge of request processing. It creates the bean
objects if required by the jsp page and calls the respective jsp page. The jsp
handles the presentation part by using the bean object. In this Model, JSP doesn’t
do any processing, Servlet creates the bean Object and calls the JSP program as
per the request made by client.
b. client
c. both a and b
d. neither a nor b
Code ……
</jsp:scriptlet>
<%
int i=9;
int k=9;
int j=k+i;
Now we will consider xml syntax and allow the above code to run:
?
<jsp:scriptlet>
int i=9;
int k=9;
int j=k+i;
36
Now consider the following example:
?
<%
int i=9;
int k=9;
int j=k+i;
%>
Sum of I an j is:<%=k%>
Ie <%= variable %> this way we can print a variable inside a jsp file. When
compared to out.println() method it is more convenient . Before we conclude this I
would like to explore one more tag which is very handy.
JSP Declaration
Now we see that the Syntax for jsp declaration will be:
?
?
<%!
}
%>
<%=add(2,3)%>
<%=add(5,4)%>
37
Servlets and JSP
Check your progress 3
Programming
1. JSP syntax can be in shape of:
a. HTML
b. word
c. XML
d. DHTML
Objects Description
38
pageContext This encapsulates use of server-specific features like
higher performance JspWriters.
a. response
b. request
c. out
d. session
39
Servlets and JSP
Programming
We see that JSP container will initially look to find myBeanAttribute attribute in
the request scope and if it’s not exist, then it will create instance of MyBean and
assign it to myBeanAttribute id variable in JSP where it will arrange an attribute
to request scope. It is noted that once bean is defined in JSP, its properties can be
achieved using jsp:getProperty action as:
<jsp:getProperty name="myBeanAttribute" property="count" />
40
Here the name attribute in jsp:getProperty is similar as id attribute in
jsp:useBean action. JSP getProperty action is restricted as its property cant be
taken out. We can use jsp:setProperty in order to arrange property values of java
bean as:
<jsp:setProperty name="myBeanAttribute" property="count" value="5" />
We see that the difference among JSP include directive and include action is
that in JSP include directive, content to other resource gets added up to form
servlet code at time of translation whereas in case of JSP include action content to
other resource gets added up to form servlet code at runtime.
We can pass parameters to the included resource using jsp:param action like
below.
We can get the param value in the included file using JSP Expression Language.
41
Servlets and JSP
Check your progress 5
Programming
1. Name the default value of the scope atribute of <jsp:usebean>.
a. page
b. application
c. session
d. request
DbForms
It allow developers to create descent web based database driven applications
in limited time and with less efforts. It is created in such a manner that logically it
is similar to RAD database building tools or Sybase PowerSite.
Jakarta Taglibs
It is an open-source repository for JSP custom tag libraries and its related
projects such as TagLibraryValidator classes and extensions to page-creation tools
to support tag libraries.
42
Google JSP Tag Library
In this Tag Library, developers and designers will able to simply insert
Google queries related to searching results, caching of pages and spelling
suggestions in any web site or application.
JCE taglib
This Tag Library is project having idea of generating JSP tag library by
allowing skilled JSP developer to have customized, branded, web based interface
for JMX enabled \"MBeans\".
EasyLDAP
The JSP web survey tag library is for making dynamic web surveys
JPivot
JPivot is a JSP custom tag library that provides an OLAP table and let users
perform typical OLAP navigations like slice and dice, drill down and roll up. It
uses Mondrian as its OLAP Server.
MicroNova YUZU JSP Tag Library
Paging, sorting and filtering data in a web environment using java, jsp and taglibs.
43
Servlets and JSP TableTag
Programming
TableTag is JSP tag library intended to build simple data entry pages, like
ASP.NET's DataGrid. It has plugable renderers for table, rows and columns, event
driven data handling, and data feeding based on java.util.List.
a. JCE Taglib
b. TableTag
c. JPivot
d. Cewolf
To explain the syntax of JSP, we have to first start with the Scriptlet. A
scriptlet contain any number of JAVA language statements, variable or method
declarations, or expressions which is valid in page scripting language.
JSP provides Standard Action tags which are applied inside JSP pages. Such
tags are used to remove or eliminate scriptlet code from JSP page as scriplet code
are technically not suggested these days.
Answers: (1-a)
44
Check your progress 2
Answers: (1-b)
Answers: (1-c)
Answers: (1-c)
Answers: (1-a)
Answers: (1-a)
3.10 Glossary
1. JSP - A server technology used to create webpage in java.
3.11 Assignment
Explain the JSP Architecture?
3.12 Activities
Study JSP Implicit Objects.
45
Servlets and JSP 3.14 Further Readings
Programming
1. Operating System Concept by Abraham Silberschatz, Peter Baer Galvin,
Greg Gagne
46
Block Summary
In this block, students have learnt and understand about the basic of Basic of
JSP Syntax and Implicit Objects. The block gives an idea on the study and
concept of basic Struts Action Classes and Model Components. The students have
be well explained on the concepts of compiling and running Servlets in Apache
Tomcat 4.0.
The block detailed about the basic idea of Threading Issues techniques. The
concept related to Struts Action Classes and Model Components will also be
explained to the students. The student will be demonstrated practically about
Architecture of the Servlet Package.
47
Servlets and JSP Block Assignment
Programming
Short Answer Questions
1. What is Struts Action Classes?
2. Explain the Threading Issues?
2. Write short note on compiling and running Servlets in Apache Tomcat 4.0?
3. Write note on configuring web.xml file for Struts?
48
Enrolment No.
1. How many hours did you need for studying the units?
Unit No 1 2 3 4
Nos of Hrs
2. Please give your reactions to the following items based on your reading of
the block:
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
49
Education is something
which ought to be
brought within
the reach of every one.
- Dr. B. R. Ambedkar