0% found this document useful (0 votes)
59 views60 pages

Object Oriented Concepts and Programming - Ii (Advance Java)

Uploaded by

maulik shah
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)
59 views60 pages

Object Oriented Concepts and Programming - Ii (Advance Java)

Uploaded by

maulik shah
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
You are on page 1/ 60

OBJECT ORIENTED CONCEPTS AND

PROGRAMMING – II (ADVANCE JAVA)


BCA - 401

BLOCK 4:
SERVLETS & JSP
PROGRAMMING

Dr. Babasaheb Ambedkar Open University


Ahmedabad
Education is something
which ought to be
brought within
the reach of every one.

- Dr. B. R. Ambedkar

Dr. Babasaheb Ambedkar Open University


‘Jyotirmay Parisar’, Opp. Shri Balaji Temple, Sarkhej-Gandhinagar Highway, Chharodi,
Ahmedabad-382 481.
OBJECT ORIENTED CONCEPTS
AND PROGRAMMING – II
(ADVANCE JAVA)

Knowledge Management and


Research Organization
Pune
Editorial Panel

Author
Prof. Rekharani Mathur

Language Editor
Mr. Vipul Shelke

Graphic and Creative Panel


Ms. K. Jamdal
Ms. Lata Dawange
Mr. Prashant Tikone

Copyright © 2015 Knowledge Management and Research Organization.


All rights reserved. No part of this book may be reproduced, transmitted or utilized
in any form or by means of, electronic or mechanical, including photocopying,
recording or by any information storage or retrieval system without written
permission from us.

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

The need to plan effective instruction is imperative for a successful


distance teaching repertoire. This is due to the fact that the instructional
designer, the tutor, the author (s) and the student are often separated by
distance and may never meet in person. This is an increasingly common
scenario in distance education instruction. As much as possible, teaching by
distance should stimulate the student's intellectual involvement and
contain all the necessary learning instructional activities that are capable of
guiding the student through the course objectives. Therefore, the course /
self-instructional material are completely equipped with everything that
the syllabus prescribes.
To ensure effective instruction, a number of instructional design
ideas are used and these help students to acquire knowledge, intellectual
skills, motor skills and necessary attitudinal changes. In this respect,
students' assessment and course evaluation are incorporated in the text.
The nature of instructional activities used in distance education self-
instructional materials depends on the domain of learning that they
reinforce in the text, that is, the cognitive, psychomotor and affective. These
are further interpreted in the acquisition of knowledge, intellectual skills
and motor skills. Students may be encouraged to gain, apply and
communicate (orally or in writing) the knowledge acquired. Intellectual-
skills objectives may be met by designing instructions that make use of
students' prior knowledge and experiences in the discourse as the
foundation on which newly acquired knowledge is built.
The provision of exercises in the form of assignments, projects and
tutorial feedback is necessary. Instructional activities that teach motor skills
need to be graphically demonstrated and the correct practices provided
during tutorials. Instructional activities for inculcating change in attitude
and behavior should create interest and demonstrate need and benefits
gained by adopting the required change. Information on the adoption and
procedures for practice of new attitudes may then be introduced.
Teaching and learning at a distance eliminates interactive
communication cues, such as pauses, intonation and gestures, associated
with the face-to-face method of teaching. This is particularly so with the
exclusive use of print media. Instructional activities built into the
instructional repertoire provide this missing interaction between the
student and the teacher. Therefore, the use of instructional activities to
affect better distance teaching is not optional, but mandatory.
Our team of successful writers and authors has tried to reduce this.
Divide and to bring this Self Instructional Material as the best teaching
and communication tool. Instructional activities are varied in order to assess
the different facets of the domains of learning.
Distance education teaching repertoire involves extensive use of self-
instructional materials, be they print or otherwise. These materials are
designed to achieve certain pre-determined learning outcomes, namely goals
and objectives that are contained in an instructional plan. Since the teaching
process is affected over a distance, there is need to ensure that students actively
participate in their learning by performing specific tasks that help them to
understand the relevant concepts. Therefore, a set of exercises is built into the
teaching repertoire in order to link what students and tutors do in the
framework of the course outline. These could be in the form of students'
assignments, a research project or a science practical exercise. Examples of
instructional activities in distance education are too numerous to list.
Instructional activities, when used in this context, help to motivate students,
guide and measure students' performance (continuous assessment)
PREFACE
We have put in lots of hard work to make this book as user-friendly
as possible, but we have not sacrificed quality. Experts were involved in
preparing the materials. However, concepts are explained in easy language
for you. We have included many tables and examples for easy
understanding.
We sincerely hope this book will help you in every way you expect.
All the best for your studies from our team!
OBJECT ORIENTED CONCEPTS AND
PROGRAMMING – II (ADVANCE JAVA)
Contents

BLOCK 1: JAVA REVIEW & SWING COMPONENTS


UNIT 1 BASIC REVIEW OF JAVA
Introduction, Java Platform Features, Java Programs and Components,
History of Java Platform, Java 2 Platform Editions, Java Platform
Environment, Setting Path and Class path, Java doc Comments
UNIT 2 Introduction to Swing
Introduction, Differences between Swing And Applets, Writing a Swing
Program, Swing Component and Containment Hierarchy, Layout
Management, Event Handling, The Action Event API

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 REMOTE METHOD INVOCATION


Introduction, The Internet Today, The World Wide Web, Internet
Service Providers, Stability and Reliability of the Web, Marketing and
Selling Products and Services, Triggering New Businesses, Others
Threats
UNIT 2 JAVABEANS
Introduction, Java Beans Concepts, The Beans Development Kit,
Writing a Simple Bean, Simple Properties, Bound Properties, Indexed
Properties, Constrained Properties
UNIT 3 JAVA NAMING AND DIRECTORY INTERFACE API
Introduction, Naming and Directory Service, Enter JNDI, JNDI
Overview, Understanding the Concepts behind JNDI Programming,
Programming with JNDI, Exploring Javax.naming package

BLOCK 4: SERVLETS & JSP PROGRAMMING

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

OBJECT ORIENTED CONCEPTS AND


PROGRAMMING – II (ADVANCE JAVA)

BLOCK 3: SERVLETS & JSP PROGRAMMING

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:

 Concept of Architecture of the Servlet Package

 Idea about Threading Issues

 Features about compiling and running Servlets in Apache Tomcat 4.0

 Idea about Struts Controller Components

 Basic of Struts Action Classes and Model Components

 Idea about configuring web.xml file for Struts

 Basic of JSP Syntax and Implicit Objects

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.3 Interacting with Clients


1.4 Threading Issues

1.5 Saving Client State


1.6 Request Dispatcher

1.7 Compiling and Running Servlets in Apache Tomcat 4.0


1.8 Let Us Sum Up

1.9 Answer for Check Your Progress


1.10 Glossary

1.11 Assignment
1.12 Activities

1.13 Case Study


1.14 Further Readings

1.0 Learning Objectives


After learning this Unit, you will be able to understand:

 Interacting with Clients

 Threading Issues

 Saving Client State

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.

1.2 Architecture of the Servlet Package


A Servlet, in its most general form, is an instance of a class which
implements the javax.servlet.Servlet interface. Most Servlets, however, extend
one of the standard implementations of that interface, namely
javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. In this tutorial
we'll be discussing only HTTP Servlets which extend the
javax.servlet.http.HttpServlet class.

In order to initialize a Servlet, a server application loads the Servlet class


(and probably other classes which are referenced by the Servlet) and creates an
instance by calling the no-args constructor. Then it calls the Servlet's
init(ServletConfig config) method. The Servlet should performe one-time setup
procedures in this method and store the ServletConfig object so that it can be
retrieved later by calling the Servlet's getServletConfig() method. This is handled
by GenericServlet. Servlets which extend GenericServlet (or its subclass
HttpServlet) should call super.init(config) at the beginning of the init method to
make use of this feature. The ServletConfig object contains Servlet parameters
and a reference to the Servlet's ServletContext. The init method is guaranteed to
be called only once during the Servlet's lifecycle. It does not need to be thread-
safe because the service method will not be called until the call to init returns.

When the Servlet is initialized, its service(ServletRequest req,


ServletResponse res) method is called for every request to the Servlet. The
method is called concurrently (i.e. multiple threads may call this method at the
same time) so it should be implemented in a thread-safe manner.

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.

Fig 1.1 Servlet's lifecycle

Check your progress 1


1. When init() method of servlet gets called?

a. when servlet is initially created.


b. whenever servlet gets invoked.

c. Both a and b
d. Neither a nor b

1.3 Interacting with Clients


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. For example, the service
method calls the doGet method shown earlier in the simple example servlet.

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

Check your progress 2


1. Which of following information is correct about HTTP Get method?
a. It sends encoded user information appended to page request.

b. It is defualt method which pass information from browser to web server.


c. Both a and b.

d. D. Neither a nor b.

1.4 Threading Issues


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. Each
thread is a sequential flow of control within the same program. Each sort
operation runs independently from the others, but at the same time.

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.

Fig 1.2 multiple threads processing

In this we see that when thread A analyse variable instanceVar, then it is


noted that thread-B just increases instanceVar. We see that the problem here
appears as thread A written to instanceVar which does not expect value to change
till thread A clearly performs. Fortunately thread-B also analyse same thing itself;
the only problem is they share the same variable. So such issue is not exclusive to
servlets, but serves as common programme problem in case of multithreading
application.
So we see that Servlet instances are essentially not thread safe for the reason
of multi threading nature of Java programming language. The Java Virtual
Machine supports working similar code by multiple threads. This is a great
performance benefit on machines which have multiple processors. This also
allows the same code to be executed by multiple concurrent users without
blocking each other.

6
Check your progress 3
1. Each thread is a sequential flow of:
a. data

b. control
c. information

d. all of above

1.5 Saving Client State


The Servlet API describes two ways to track client state:

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.

When a client application (e.g., a Web browser) receives a cookie from a


web server, the client application stores the cookie locally. Upon subsequent
request to the web server, the cookie will be returned.

7
Servlets and JSP
Programming

Fig 1.3 Cookie Transmission Over the Network

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.

Check your progress 4


1. The other form of client application is:
a. web application

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.

 public void forward(ServletRequest request,ServletResponse response)


throws Servlet Exception,java.io.IOException:Forwards a request from a
servlet to another resource (servlet, JSP file, or HTML file) on the server.

 public void include(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Includes the content
of a resource (servlet, JSP page, or HTML file) in the response.

Fig 1.4 Forward method

As shown in fig 1.5, response of second servlet is included in the response


of the first servlet that is being sent to the client.

Fig 1.5 include method

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

b. Codes starting from 300


c. Codes starting from 400

d. Codes starting from 500

1.7 Compiling and Running Servlets in Apache Tomcat


4.0
To create a Servlet application you need to follow the below mentioned
steps. These steps are common for all the Web server. Apache Tomcat is an open
source web server for testing servlets and JSP technology.

Creating the Directory Structure


Sun Microsystem defines a unique directory structure that must be followed
to create a servlet application.

10
Fig 1.7 creating directory

Creating a Servlet
There are three different ways to create a servlet.

 By implementing Servlet interface

 By extending GenericServlet class

 By extending HttpServlet class

But mostly a servlet is created by extending HttpServlet abstract class. As


discussed earlier HttpServlet gives the definition of service() method of the
Servlet interface. The servlet class that we will create should not override
service() method. Our servlet class will override only doGet() or doPost() method.

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

Create Deployment Descriptor


Deployment Descriptor(DD) is an XML document that is used by Web
Container to run Servlets and JSP pages. DD is used for several important
purposes such as:

Start the Server


Double click on the startup.bat file to start your Apache Tomcat Server Or
execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat

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.

 Right Click on My Computer, go to Properites.

 Go to Advanced Tab and Click on Environment Variables... button.

 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.

Run Servlet Application


Open Browser and type http:localhost:8080/First/hello

Fig 1.8 Running Application


12
Check your progress 6
1. The other form of Apache Tomcat is:
a. Jakarta Tomcat

b. Google Tomcat
c. Server tomcat

d. none of these

1.8 Let Us Sum Up


In this unit we have learnt that Servlets are modules of Java code that run in
a server application to answer client requests.
In order to initialize a Servlet, a server application loads the Servlet class
and creates an instance by calling the no-args constructor.

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.

RequestDispatcher is an interface, implementation of which defines an


object which can dispatch request to any resources on the server.

1.9 Answer for Check Your Progress

Check your progress 1

Answers: (1-a)

Check your progress 2

Answers: (1-c)
13
Servlets and JSP Check your progress 3
Programming
Answers: (1-c)

Check your progress 4

Answers: (1-a)

Check your progress 5

Answers: (1-c)

Check your progress 6

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.

1.13 Case Study


Study the Compiling process about Servlets in Apache Tomcat 4.0.

1.14 Further Readings


1. Operating System Concept by Abraham Silberschatz, Peter Baer Galvin,
Greg Gagne

14
UNIT 2: INTRODUCTION TO STRUTS
Unit Structure
2.0 Learning Objectives

2.1 Introduction
2.2 Struts Controller Components

2.3 Struts Action Classes


2.4 Struts Model Components

2.5 The Struts View Components


2.6 Configuring the Struts Application

2.7 Configuring the web.xml file for Struts


2.8 Let Us Sum Up

2.9 Answer for Check Your Progress


2.10 Glossary

2.11 Assignment
2.12 Activities

2.13 Case Study


2.14 Further Readings

2.0 Learning Objectives


After learning this Unit, you will be able to:

 Struts Action Classes

 Struts Model Components

 The Struts View Components

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).

2.2 Struts Controller Components


The controller is responsible for intercepting and translating user input into
actions to be performed by the model. The controller is responsible for selecting
the next view based on user input and the outcome of model operations. The
Controller receives the request from the browser, invoke a business operation and
coordinating the view to return to the client. The controller is implemented by a
java servlet, this servlet is centralized point of control for the web application. In
struts framework the controller responsibilities are implemented by several
different components like:

 The ActionServlet Class

 The RequestProcessor Class

 The Action Class


Controller components coordinate activities in the application. This may
mean taking data from the user and updating a database through a Model
component, or it may mean detecting an error condition with a back-end system
and directing the user through special error processing. Controller components
accept data from the users, decide which Model components need to be updated,
and then decide which View component needs to be called to display the results.

16
Introduction to
Struts

Fig 2.1 Controller component

One of the major contributions of Controller components is that they allow


the developer to remove much of the error handling logic from the JSP pages in
their application. This can significantly simplify the logic in the pages and make
them easier to develop and maintain.

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.

Check your progress 1


1. Struts is a
a. Technology

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.

Check your progress 2


1. OGNL is:
a. powerful expression language used to reference data on valuestack

b. used for manipulation of data on the ValueStack


c. helps in data transfer and type conversion.

d. all of above

2.4 Struts Model Components


The model shows business data for an application that closely resembles
real-world entities and business processes for organization. The model
components of an application possibly are the most expensive software artefacts’
to an organization. The model take account of business entities in addition to the
rules that preside over access to furthermore modification of the data. It’s vital
that this be kept in a single location in order to maintain valid data integrity,
reduce redundancy, and increase reusability.
The model should remain independent of the type of client that’s being used
to access the business objects and their associated rules.
In struts, model describes an application’s data having logic for accessing
and manipulating data. In this, any data which is part of persistent state of the
application be kept inside the model objects. The business objects update the
20
application state. Action Form bean represents the Model state at a session or
request level, and not at a persistent level. It is noted that model services are
accessed by controller for querying or effecting changes in model state. The
model notifies view when a state change occurs in the model. The JSP file reads
information from the ActionForm bean using JSP tags.

The Struts structure doen't offer much in way of creating model


components. It is the Enterprise JavaBeans (EJB), Java Data Objects(JDO) and
JavaBeans which uses as model. Struts structure doesn't restrict to single
particular model implementation.
Struts framework helps for developing the web based applications. Struts
java framework is one of the most popular framework for web based
applications.Java servlet, JavaBeans, ResourceBundles and XML etc are the
Jakarta commons packages used for accomplishing this purpose. This is an open
source implementation of MVC pattern for the development of web based
application. The features of this type of framework are, More robust or reliable
architecture Helps for development of application of any size Easy to design
Scalable Reliable web application with java.

Fig 2.2 Framework

21
Servlets and JSP Strut implements the Model-View-Controller (MVC) design pattern.
Programming

Fig 2.3 MVI model

Here we see that a model will include core of application’s functions. It


hush-up the state of the application. Sometimes the only functionality it contains
is state. Model category not bothered about the view or controller category.

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

Check your progress 3


1. In struts, which class is responsible to converts data types from string?

a. StrutsTypeConverter
b. StringTypeConverter

c. Both of the above


d. None of the above

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

 Data transfer objects

 Struts ActionForms

 JavaServer Pages

 Custom tags

 Java resource bundles

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

2.6 Configuring the Struts Application


Struts application is a normal web application that carries Struts libraries
and configuration files. Such application can be created in similar manner as you
create any other web application in IDE with the help of New Web Application
wizard where extra step shows Struts libraries along with configuration files
which can be added in an application.

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

Fig 2.5 selecting project

The Struts-specific configuration files, as well as the application's


deployment descriptor, are conveniently placed within the Configuration Files
folder. Open the deployment descriptor. In order to handle Struts processing, a
mapping is provided for the Struts controller servlet.

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.

FilterDispatcher Example (web.xml)

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.

Check your progress 6


1. web.xml configuration file in struts is:
a. J2EE configuration file

b. J2SE configuration file


c. JEE configuration file

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.

Controller components coordinate activities in the application. This may


mean taking data from the user and updating a database through a Model
component, or it may mean detecting an error condition with a back-end system
and directing the user through special error processing.

Struts application is a normal web application that carries Struts libraries


and configuration files. Such application can be created in similar manner as you
create any other web application in IDE with the help of New Web Application
wizard where extra step shows Struts libraries along with configuration files
which can be added in an application.

2.9 Answer for Check Your Progress

Check your progress 1

Answers: (1-b)

Check your progress 2

Answers: (1-d)

Check your progress 3

Answers: (1-a)

Check your progress 4

Answers: (1-b)

Check your progress 5

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.

2.13 Case Study


Generalised the basic of Struts View Components.

2.14 Further Readings


1. Operating System Concept by Abraham Silberschatz, Peter Baer Galvin,
Greg Gagne
2. Programming Be Operating System by Dan Sydow

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.3 JSP Architecture


3.4 JSP Syntax Basics

3.5 JSP Implicit Objects


3.6 Standard Actions

3.7 JSP Tag Libraries


3.8 Let Us Sum Up

3.9 Answer for Check Your Progress


3.10 Glossary

3.11 Assignment
3.12 Activities

3.13 Case Study


3.14 Further Readings

3.0 Learning Objectives


After learning this Unit, you will be able tounderstand:

 JSP Architecture

 JSP Syntax Basics

 JSP Implicit Objects

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)

before it sent to user who requested it.

3.2 Comparing JSP with ASP


JSP is Java Server Pages while ASP is Active Server Pages which are two
commonly used server side scripting languages used today in web development.
There are some differences among the two:

Java Server Pages Active Server Pages

JSP was created by Sun Microsystems ASP was created by Microsoft


as an extension to Java

It is a freeware software It is requires money to buy software

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

3.3 JSP Architecture


Depending on the location of request processing, Servlet OR JSP carries two
architectures which are:

 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.

Fig 3.1 Architecture Model 1

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.

Fig 3.2 Architecture Model I1

Check your progress 2


1. the bean object is created by Java on request of:
a. server

b. client
c. both a and b

d. neither a nor b

3.4 JSP Syntax Basics


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
35
Servlets and JSP declarations, or expressions which is valid in page scripting language. Consider
Programming the syntax of scriptlet:
?

<% code goes here…..%>


On other hand code rendered inside <% %> these tags considered as jsp
code; and compiled as JSP code. We have XML equivalent of syntax which is:
?
<jsp:scriptlet>

Code ……
</jsp:scriptlet>

Now we will write a simple jsp file:


?

<%
int i=9;

int k=9;
int j=k+i;

out.println("sum of i and j is:"+j);


%>

We see that output of this is:


Sum of I and j is:18

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;

out.println("sum of i and j is:"+j);


</jsp:scriptlet>
In jsp there is a shortcut for out.println() method.

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:
?

<%! Declaration goes here ….%>


Here we see that the declaration tags is applied to declare public method so
that those methods are available to all other script bloc.
Now again consider an example.

?
<%!

public int add(int a,int b){


return a+b;

}
%>

<%=add(2,3)%>
<%=add(5,4)%>

In this way we can call add() method in anywhere in the page.

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

3.5 JSP Implicit Objects


In JSP, we see that there are nine directly defined variables that are called
as implicit objects such as:

Objects Description

request This is the HttpServletRequest object associated with


the request.

response This is the HttpServletResponse object associated


with the response to the client.

out This is the PrintWriter object used to send output to


the client.

session This is the HttpSession object associated with the


request.

application This is the ServletContext object associated with


application context.

config This is the ServletConfig object associated with the


page.

38
pageContext This encapsulates use of server-specific features like
higher performance JspWriters.

page This is simply a synonym for this, and is used to call


the methods defined by the translated servlet class.

Exception The Exception object allows the exception data to be


accessed by designated JSP.

Check your progress 4


1. Which object is applied to send request to client?

a. response
b. request

c. out
d. session

3.6 Standard Actions


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. It's considered to be terrible practice to
apply java code straight into JSP page. Standard tags starts with jsp prefix. There
are many JSP Standard Action tag which are used to perform some specific task.
Following are some of the JSP Standard Action Tags:

39
Servlets and JSP
Programming

JSP Bean Action:


JSP provide jsp:useBean shown below to apply in JSP pages to get bean object.

<jsp:useBean id="myBeanAttribute" class="com.journaldev.MyBean"


scope="request" />

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" />

In order to arrange the property only when jsp:useBean creates current


instance, then we can use jsp:setProperty inside the jsp:useBean to achieve this,
something like below code snippet.

JSP Include Action


We can also apply jsp:include action to include other resource in JSP page.
The syntax of jsp:include action is:
<jsp:include page="header.jsp" />

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.

JSP Forward Action


Further we can see that using jsp:forward action tag is normally applied to
forward the request to other resource so as to handle it. It’s syntax is:

<jsp:forward page="login.jsp" />

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

3.7 JSP Tag Libraries


The syntax for applying tag libraries is same as for standard actions except
that tag names and attributes are defined in tag library itself instead of JSP
standard. Each tag library is linked with prefix that uses taglib directive to map
prefix to URI identifying tag library.
JSP introduce method of extending JSP tags that are related as tag libraries.
Such libraries will allow extra tags that is same as jsp:include or jsp:forward,but
with several other prefixes apart from jsp: and its features. There are different
types of Tag libraries such as:

Display tag library


It is an open source suite of custom tags which shows high level web
presentation patterns that can be applied in MVC model. It gives significant
amount of functions.

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

It is also an Open Source JSP tags and expression language EL functions


that communicates with Sun's JCE library in order to show high-level strong
encryption to JSP applications. In this, classes are arranged such that it can be
applied for other non-JSP projects.
Cewolf

Cit is mostly applied inside Servlet/JSP based web application to implant


complex graphical charts into web page. It shows complete featured tag library
which explains properties of chart.
WebJMX

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

EasyLDAP is JSP tag library for LDAP operations


JSP Survey Library

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

MicroNova YUZU is a BSD-licensed JSP tag library designed to augment


JSTL (JSP Standard Tag Library) using EL (Expression Language). YUZU is
compatible with both JSP 1.2 and JSP 2.0 specifications (tomcat 4.x/5.x).
ValueList

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.

Check your progress 6


1. Which tag library uses EL function?

a. JCE Taglib
b. TableTag

c. JPivot
d. Cewolf

3.8 Let Us Sum Up


In this unit we have learnt that JSP is a server side technology which helps
to create a webpage dynamically using java as the programming language.
JSP is Java Server Pages while ASP is Active Server Pages which are two
commonly used server side scripting languages used today in web development.

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.

3.9 Answer for Check Your Progress

Check your progress 1

Answers: (1-a)

44
Check your progress 2

Answers: (1-b)

Check your progress 3

Answers: (1-c)

Check your progress 4

Answers: (1-c)

Check your progress 5

Answers: (1-a)

Check your progress 6

Answers: (1-a)

3.10 Glossary
1. JSP - A server technology used to create webpage in java.

2. ASP - It is Active Server Pages used to design webpages.

3.11 Assignment
Explain the JSP Architecture?

3.12 Activities
Study JSP Implicit Objects.

3.13 Case Study


Study the types of JSP Tag Libraries.

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?

3. Write note on Struts Controller Components?


4. Write short note on JSP Syntax and Implicit Objects?

Long Answer Questions


1. Write short notes on Architecture of the Servlet Package?

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:

3. Any Other Comments


………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

………………………………………………………………………………………………

49
Education is something
which ought to be
brought within
the reach of every one.

- Dr. B. R. Ambedkar

Dr. Babasaheb Ambedkar Open University


‘Jyotirmay Parisar’, Opp. Shri Balaji Temple, Sarkhej-Gandhinagar Highway, Chharodi,
Ahmedabad-382 481.

You might also like