0% found this document useful (0 votes)
51 views

Unit 1 (2024)

Uploaded by

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

Unit 1 (2024)

Uploaded by

Kavya Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Noida Institute of Engineering and Technology, Greater Noida

Advance Java Programming(ACSAI0612)


Unit 1-JDBC and Servlet
Course Details
( B Tech 6th Sem)

Shweta Singh
Assistant Professor
CSE-AI
Evaluation Scheme

Shweta Singh ACSAI0612 Advance


05/14/2024 2
Java Programming Unit 1
Syllabus Unit -1

JDBC: Introduction, JDBC Driver, DB Connectivity, Driver Manager,


Connection, Statement, Result Set, Prepared Statement, Transaction
Management, Stored Procedures.

Servlet: Servlet Overview, Servlet API, Servlet Interface, Generic Servlet,


HTTP Servlet, Servlet Life Cycle, Redirect requests to other resources, Session
Tracking, Event and Listener.

Shweta Singh ACSAI0612 Advance


05/14/2024 3
Java Programming Unit 1
Syllabus Unit -2

JSP: Introduction, Overview, JSP Scriptlet Tag, JSP expression Tag, JSP
declaration Tag, Life Cycle of JSP, JSP API, Implicit Objects: JSP
request, JSP response, JSP config, JSP session, JSP Application, JSP
PageContext; JSP Page, JSP Exception.

Shweta Singh ACSAI0612 Advance


05/14/2024 4
Java Programming Unit 1
Syllabus Unit -3

Spring 5.0: Spring Core Introduction and Overview, Managing Beans, The
Spring Container, The Factory Pattern, Dependency Injection (DI), Spring
Managed Bean Lifecycle, Constructor Injection, Metadata/Configuration:
Life Cycle Annotations, Java Configuration, XML Free configuration.

Shweta Singh ACSAI0612 Advance


05/14/2024 5
Java Programming Unit 1
Syllabus Unit -4

Spring MVC: Introduction/Developing Web Application with Spring MVC,


Advanced Techniques, Spring Controllers

Spring Boot: Spring Boot Starters, CLI, Application Class, Logging, Auto
Configuration Classes, Spring Boot dependencies, Spring data JPA introduction and
Overview

Shweta Singh ACSAI0612 Advance


05/14/2024 6
Java Programming Unit 1
Syllabus Unit -5

JPA: Introduction & overview of data persistence, Overview of ORM tools,


Understanding JPA, Entities: Requirement for Entity Class, Persistent Fields
and Properties, Primary keys in Entries, Entity Management, Querying Entities,
Entities Relationships

Shweta Singh ACSAI0612 Advance


05/14/2024 7
Java Programming Unit 1
Text Books

Text books:

1.Bhave, “Programming with Java”, Pearson Education, 2009

2.Herbert Schieldt, “The Complete Refernce: Java”, TMH, 1991

3.Hans Bergsten, “Java Server Pages”, SPD O’Really, 1985

4.Katy Sierra and Bert Bates, “Head First: Java”, O’Really, 2008

5.Katy Sierra and Bert Bates, “Head First: Servlets & JSP”, O’Really , 2008

Shweta Singh ACSAI0612 Advance


05/14/2024 8
Java Programming Unit 1
Course Objective

To provide the ability to design console based, GUI based ,web based applications.


To design and develop the dynamic web sites using, Servlet and jsp.


To understand the concept of business logic to develop the enterprises application
by Spring framework.


To apply the MVC design pattern in developing a live project.


To learn the concept of database handling in java and apply this concept in
transactional processing based project.

Shweta Singh ACSAI0612 Advance


05/14/2024 9
Java Programming Unit 1
Course Outcome

At the end of the semester, student will be able to:


Course CO Description Blooms’
Outcomes Taxonomy
(CO)
Understand the concept of implementing the connection between Java and Database using K2, K4
CO1
JDBC.
Understand, analyze and apply the role of mark up languages like HTML, DHTML, and XML in K2, K3
CO2
the workings of the web and web applications.

Analyze and design the Spring Core Modules and DI to configure and wire beans (application K4,K5
CO3
objects) together

Design Model View Controller architecture and ready components that can be used to develop K2, K3, K6
CO4
flexible and loosely coupled web applications.

CO5 Deploy JPA to Map, store, retrieve, and update data from java objects to relational databases and K5
vice versa.

Shweta Singh ACSAI0612 Advance


05/14/2024 10
Java Programming Unit 1
Program Outcome

1. Engineering knowledge:
2. Problem analysis:
3. Design/development of solutions:
4. Conduct investigations of complex problems:
5. Modern tool usage:
6. The engineer and society:
7. Environment and sustainability:
8. Ethics:
9. Individual and team work:
10. Communication:
11. Project management and finance:
Shweta Singh ACSAI0612 Advance
05/14/2024
12. Life-long learning 11
Java Programming Unit 1
CO-PO Mapping
Mapping of Course Outcomes and Program Outcomes:

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

ACSE 3 3 2 3 3 3 2 3 3 3 2 3
0601.1

ACSE 3 2 3 2 3 2 2 2 3 3 3 3
0601.2
ACSE 3 3 3 2 3 3 2 3 3 3 2 3
0601.3
ACSE 3 3 3 2 3 3 2 3 3 3 3 3
0601.4
ACSE 3 3 3 2 3 2 2 3 3 3 3 3
0601.5
Averag 3 2.8 2.8 2.2 3 2.6 2 2.8 3 3 2.6 3
Shweta Singh ACSAI0612 Advance
05/14/2024 12
Java Programming Unit 1
e
Program Specific Outcomes

PSO1: Work as a software developer, database administrator, tester


or networking engineer for providing solutions to the real world and


industrial problems.
PSO2:Apply core subjects of information technology related to data

structure and algorithm, software engineering, web technology,


operating system, database and networking to solve complex IT
problems.
PSO3: Practice multi-disciplinary and modern computing techniques

by lifelong learning to establish innovative career.


PSO4: Work in a team or individual to manage projects with ethical

concern to be a successful employee


Shweta Singh ACSAI0612 Advance
or employer in IT industry.
05/14/2024 13
Java Programming Unit 1
COs and PSOs Mapping

Mapping of Program Specific Outcomes and Course Outcomes:

Course Outcomes Program Specific Outcomes

PSO1 PSO2 PSO3 PSO4

ACSE0601.1 3 3 2 3

ACSE0601.2 3 3 3 2

ACSE0601.3 3 3 2 2

ACSE0601.4 3 2 3 2

ACSE0601.5 3 2 2 2

AVG 3 2.6 2.4 2.2

*3= High *2= Medium *1 = Low


Shweta Singh ACSAI0612 Advance
05/14/2024 14
Java Programming Unit 1
Program Educational Objectives

PEO1: able to apply sound knowledge in the field of information technology to


fulfill the needs of IT industry.

PEO2:able to design innovative and interdisciplinary systems through latest


digital technologies.

PEO3: able to inculcate professional and social ethics, team work and leadership
for serving the society.

PEO4: able to inculcate lifelong learning in the field of computing for successful
career in organizations and R&D sectors.
Shweta Singh ACSAI0612 Advance
05/14/2024 15
Java Programming Unit 1
End Semester Question Paper Template

Shweta Singh ACSAI0612 Advance


05/14/2024 16
Java Programming Unit 1
End Semester Question Paper Template

Shweta Singh ACSAI0612 Advance


05/14/2024 17
Java Programming Unit 1
Prerequisites

Prerequisites:


Having knowledge about core java concepts.


Basic knowledge abut the JDBC concepts.


Basic knowledge about the business logic.


Basic knowledge about MVC design pattern

Shweta Singh ACSAI0612 Advance


05/14/2024 18

Basic knowledge about RDBMS query.
Java Programming Unit 1
Brief Introduction to Subject


Advance Java Programming provides libraries to understand the concept of Client-Server architecture for web-
based applications.


We can also work with web and application servers such as Apache Tomcat and Glassfish Using these servers,
we can understand the working of HTTP protocol.


It provides a set of services, API and protocols, that provides the functionality which is necessary for
developing multi-tiered application, web-based application.


There is a number of advance Java frameworks like, Spring, Hibernate, Struts, that enables us to develop
secure transaction-based web applications such as banking application, inventory management application.


https://youtu.be/96xF9phMsWA


https://youtu.be/Zopo5C79m2k

Shweta Singh ACSAI0612 Advance


05/14/2024 19
Java Programming Unit 1
Topic Mapping with Course Outcome

Topics Course outcome


 JDBC: Introduction, JDBC Driver,
DB Connectivity, Driver CO1
Manager, Connection,
Statement, Result Set, Prepared
Statement
CO1
 Transaction Management,
Stored Procedures.

 Servlet: Servlet Overview, CO2


Servlet API, Servlet Interface,
Generic Servlet, HTTP Servlet,
Servlet Life Cycle.
CO2
 Redirect requests to other
Shweta Singh ACSAI0612 Advance
05/14/2024 20
resources, SessionUnit
Java Programming Tracking,
1
Unit 1 Content

JDBC: Introduction

JDBC Driver

DB Connectivity

Driver Manager and Connection classes

Statement, Result Set, Prepared Statement, and interface

Transaction Management and Stored Procedures.

Servlet Overview and Servlet API

Servlet Interface, Generic Servlet and HTTP Servlet with Servlet Life Cycle

Redirect requests to other resources, Session Tracking, Event and Listener


Shweta Singh ACSAI0612 Advance
05/14/2024 21
Java Programming Unit 1
Unit Objective

Objective of Unit 1:

To understand the concepts of JDBC(Java Database Connectivity) driver

To understand the use of various types of SQL command in JDBC connectivity.

To understand the concepts of Statement and PreparedStatement interface

To learn the concepts of stored procedure creation in JDBC.

To understand the concepts of Generic Servlet and HTTP Servlet

To understand the concepts of Redirecting the HTTP request

To understand the concepts of session and event handling.

Shweta Singh ACSAI0612 Advance


05/14/2024 22
Java Programming Unit 1
Objective of the above topics:
• To understand the concepts JDBC

• To understand the concepts of preparing class of JDBC

• To understand the concepts of various types of driver in JDBC

• To understand the concepts of Statement and PreparedStatement.

• To understand the concepts of transaction management

Shweta Singh ACSAI0612 Advance


05/14/2024 23
Java Programming Unit 1
Java Database Connectivity

How to get started with JDBC


JDBC Definition
• JDBC: • JDBC API Standardizes:
Java Database Connectivity
• It provides a standard library for • Way to establish connection to
Java programs to connect to a database
database and send it commands • Approach to initiating queries
using SQL • Method to create stored
• It generalizes common database procedures
access functions into a set of • Data structure of the query
common classes and methods result
• Abstracts vendor specific details
into a code library making the
connectivity to multiple databases
transparent to user
What is JDBC?
JDC acts as an interface or channel between your Java program and databases , so
that a programmer can send data from Java code and store it in the database for
future use.

Reference : https://www.google.com/url?sa=i&url=https%3A%2F%2Fptop.only.wip.la%3A443%2Fhttps%2Fwww.infoworld.com%2Farticle%2F3388036%2Fwhat-is-jdbc-introduction-to-java-database-
connectivity.html&psig=AOvVaw1pj_8eVXEcI75Z8ZGaLVAg&ust=1705997928122000&source=images&cd=vfe&opi=89978449&ved=2ahUKEwiazpvVx_CDAxWHcWwGHd2dDGgQr4kDegQIARBS
JDBC API

Two main packages java.sql and javax.sql


Java.sql contains all core classes required for accessing database
(Part of Java 2 SDK, Standard Edition)
Javax.sql contains optional features in the JDBC 2.0 API
(part of Java 2 SDK, Enterprise Edition)

Javax.sql adds functionality for enterprise applications


DataSources
JNDI
Connection Pooling
Rowsets
Distributed Transactions
JDBC Architecture

JDBC Consists of two parts:
• JDBC API, a purely Java-based API
• JDBC Driver Manager, which communicates with
vendor-specific drivers that perform the real
communication with the database

Translation to the vendor format occurs on the client
• No changes needed to the server
• Driver (translator) needed on client
JDBC Drivers

JDBC uses drivers to translate generalized JDBC calls into vendor-
specific database calls
• Drivers exist for most popular databases
• Four Classes of JDBC drivers exist
Type I
Type II
Type III
Type IV

29
JDBC Drivers (Type I: JDBC-ODBC Bridge Driver)
Type I driver provides mapping between JDBC and access API of a database

The access API calls the native API of the database to establish communication

A common Type I driver defines a JDBC to ODBC bridge


• ODBC is the database connectivity for databases
• JDBC driver translates JDBC calls to corresponding ODBC calls
• Thus if ODBC driver exists for a database this bridge can be used to communicate with the database from a Java application

Inefficient and narrow solution


• Inefficient, because it goes through multiple layers.
• Narrow, since functionality of JDBC code limited to whatever ODBC supports.
Driver (Type

ODBC API
Native API
Database
API
Client Specific Protocol
I)

Protocol
Application Database
JDBC Open Database Connectivity (ODBC)

ODBC Interface

A standard database access method developed by the SQL
Access group in 1992.
• The goal of ODBC is to make it possible to access any data
from any application, regardless of which database
management system (DBMS) is handling the data.
• ODBC manages this by inserting a middle layer, called a
database driver , between an application and the DBMS.
• The purpose of this layer is to translate the application's
data queries into commands that the DBMS understands.
• For this to work, both the application and the DBMS must
be ODBC-compliant, that is, the application must be
capable of issuing ODBC commands and the DBMS must
be capable of responding to them.
JDBC
Drivers (Type II: Native Driver)

Type II driver communicates directly with native API
• Type II makes calls directly to the native API calls
• More efficient since there is one less layer to contend with (i.e. no ODBC)
• It is dependent on the existence of a native API for a database

Driver (Type II)

Native API
Client
Application Database
API Database
Protocol Specific Protocol
JDBC Drivers (Type III: Network Protocol Driver)

Type III driver make calls to a middleware component running on another server
• This communication uses a database independent net protocol
• Middleware server then makes calls to the database using database-specific protocol
• The program sends JDBC call through the JDBC driver to the middle tier
• Middle-tier may use Type I or II JDBC driver to communicate with the database.

Driver (Type
III)

Client Middlewar
Application Net Protocol e Server Database Database
Specific Protocol
JDBC Drivers (Type III: Network Protocol Driver)

Type III driver make calls to a middleware component running on another server
• This communication uses a database independent net protocol
• Middleware server then makes calls to the database using database-specific protocol
• The program sends JDBC call through the JDBC driver to the middle tier
• Middle-tier may use Type I or II JDBC driver to communicate with the database.

Driver (Type
III)

Client Middlewar
Application Net Protocol e Server Database Database
Specific Protocol
JDBC Drivers (Type III: Network Protocol Driver)

Type III driver make calls to a middleware component running on another server
• This communication uses a database independent net protocol
• Middleware server then makes calls to the database using database-specific protocol
• The program sends JDBC call through the JDBC driver to the middle tier
• Middle-tier may use Type I or II JDBC driver to communicate with the database.

Driver (Type
III)

Client Middlewar
Application Net Protocol e Server Database Database
Specific Protocol
Drivers (Type IV : Thin Driver or Oracle Driver)


Type IV driver is an all-Java driver that is also called a thin driver
• It issues requests directly to the database using its native protocol
• It can be used directly on platform with a JVM
• Most efficient since requests only go through one layer
• Simplest to deploy since no additional libraries or middle-ware

Driver (Type
IV)
Client
Application Database Specific Database
Protocol
What we need to Perform JDBC Connection?
Requirements of JDBC Connection:

3 Database:
1 JDK:
A database is an organized collection of structured
The JDK is the development platform information, or data, typically stored electronically in a
for building Java applications. Install computer system. A database is usually controlled by a
a JDK in your development database management system (DBMS).
environment and use it to compile a
Java program. Oracle 11g /MySql

2 IDE: .Jar file :


4
A Java integrated development JAR (Java Archive) is a platform-independent file
environment (IDE) is a software format that aggregates many files into one. Multiple
application that provides Java applets and their requisite components (.class
comprehensive facilities to computer files, images and sounds) can be bundled in a JAR file.
programmers for software It is fully extensible.
development in the Java
programming language.
An IDE typically includes a source
code editor, build automation tools,
and a debugger.
JDBC Conceptual Components

Driver Manager: Loads database drivers and manages connections between the
application and the driver

Driver: Translates API calls into operations for specific database

Connection: Session between application and data source

Statement: SQL statement to perform query or update

Metadata: Information about returned data, database, & driver

Result Set: Logical set of columns and rows of data returned by executing a statement
Creates Creates Creates
DriverManager Connection Statement Result Set

Driver
Established
Link to DB

Database
Steps to Connect Java Application with Database
Below are the steps that explains how to connect to Database in Java:

Step 1 – Import the Packages.

Step 2 – Load the drivers using the forName() method .

Step 3 – Register the drivers using DriverManager.

Step 4 – Establish a connection using the Connection class object.

Step 5 – Create a statement.

Step 6 – Execute the query.

Step 7 – Close the connections.


Register the driver class
1. The forName() method of Predefined Class class is used to register/connect to the Database. This method
is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundExceptio


n
How to use this function in code

Class.forName("oracle.jdbc.driver.OracleDriver");
Create the connection object
To Create the connection Object we need to use the Connection Interface &
The getConnection() method of DriverManager class is used to establish connection with the database.

Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String password) throws SQLException

How to use this function in code

Connection con
=DriverManager.getConnection(“jdbc:Oracle:thin:@localhost:1521:xe”,”Username”,”Password”);
Create the Statement object
The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException

How to use

Statement stmt=con.createStatement();
Execute the query
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLExceptio


n

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

con.close();
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5 following steps.
So we need to know following information for the oracle database:

Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
AP driver
API database server IP address
Service name
Connection URL: The connection URL for the oracle10G database is jdbc:oracle:thin:@localhost:1521:xe

Username: The default username for the oracle database is system.

Password: It is the password given by the user at the time of installing the oracle database.
Statement interface
The Statement interface provides methods to execute queries with the database. The statement interface is a factory of
ResultSet i.e. it provides factory method to get the object of ResultSet.

Methods of Statement interface:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of
ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update,
delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.
Methods of ResultSet interface
1) public boolean next(): is used to move the cursor to the one row next from the current
position.
2) public boolean previous(): is used to move the cursor to the one row previous from the
current position.
3) public boolean first(): is used to move the cursor to the first row in result set object.
4) public boolean last(): is used to move the cursor to the last row in result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified row number in the
ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row number in the
ResultSet object, it may be positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column index of the current
row as int.
8) public int getInt(String columnName): is used to return the data of specified column name of the current
row as int.
9) public String getString(int columnIndex): is used to return the data of specified column index of the current
row as String.
10) public String getString(String columnName): is used to return the data of specified column name of the current
PreparedStatement interface
The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.

Eg:

String sql="insert into emp values(?,?,?)";

(?) for the values. Its value will be set by calling the setter methods of PreparedStatement.

Why use PreparedStatement?

• Improves performance: The performance of the application will be faster if you use PreparedStatement
interface because query is compiled only once.
• The prepareStatement() method of Connection interface is used to return the object of PreparedStatement.

Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}
Methods of PreparedStatement interface

Method Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String value) sets the String value to the given parameter index.

public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.

public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.

public int executeUpdate() executes the query. It is used for create, drop, insert, update,
delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet.
Pseodu code:

PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?");


stmt.setString(1,"SS”);//1 specifies the first parameter in the query i.e. name
stmt.setInt(2,001);

int i=stmt.executeUpdate();
System.out.println(i+" records updated");
ResultSetMetaData Interface
• metadata means data about data i.e. we can get further information from the data.
• ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.

Methods of ResultSetMetaData

Method Description
public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet
object.
public String getColumnName(int index)throws it returns the column name of the specified column
SQLException index.
public String getColumnTypeName(int index)throws it returns the column type name for the specified index.
SQLException
public String getTableName(int index)throws it returns the table name for the specified column index.
SQLException
ResultSetMetaData…………
The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData.

Syntax:
public ResultSetMetaData getMetaData()throws SQLException
To add or import a jar files in your Eclipse
IDE
Try it yourself with steps on the right:

1 Right click on your project.

2 Select Build Path.

3 Click on Configure Build Path.

4 Click on Libraries and select Add External JARs.

5 Select the jar file from the required folder.

6 Click and Apply and Ok.


Servlet Syllabus
• Servlet: Servlet Overview, Servlet API, Servlet Interface, Generic Servlet,
HTTP Servlet, Servlet Life Cycle, Redirect requests to other resources,
Session Tracking, Event and Listener.
Servlet Overview

Servlet technology is used to create a web application (resides at server side and generates
a dynamic web page).

Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the web server, process the
request, produce the response, and then send a response back to the web server.

The properties of Servlets are as follows:

Servlets work on the server side.

Servlets are capable of handling complex requests obtained from the web server.


Servlet is an API that provides many interfaces and classes including documentation.

Servlet is an interface that must be implemented for creating any Servlet.


Servlet is a class that extends the capabilities of the servers and responds to the incoming

requests. It can respond to any requests.

Servlet is a web component that is deployed on the server to create a dynamic web page.

Servlet Overview………..

Classes that dynamically process requests and construct responses


Dynamically generate html pages in response to requests
May also send data in other forms like XML or serialized Java objects
Run in a servlet container and have access to services that the container provides

In an application processing of each request will normally be done by a different


servlet.
e.g. search catalog, check out, confirm order etc.

Client of the servlet can be any of the following


Browser
Applet
Java Application
Advantages of Servlets

The advantages of Servlet are as follows:


Better performance: because it creates a thread for each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection etc.
Secure: because it uses java language.
Servlet Life Cycle
Servlet Container

Create Thread Pool Thread


Thread

Instantiate servlet
Servlet
Call init ( ) method Perform
HTTP Request 1 Initialization
Allocate request to thread Call service ( ) method

HTTP Request 2
Allocate request to thread Call service ( ) method Perform Service
Shutdown
Initiated
Block all further requests Wait for
HTTP Response active threads to end Perform Service
1
Terminate thread pool

HTTP Response call destroy ( ) method


Perform
2 cleanup
terminate servlet
Servlet destroyed &
garbage collected
Container shutdown
Servlet API

Contained in two packages


javax.servlet
javax.servlet.Http

Contains 20 interfaces and 16 classes


Prevalence of interfaces allows servlet implementation to be customized
to container
Java Servlets

Javax.servlet package can be extended for use with any application layer
protocol
http is the most popularly used protocol
Javax.servlet.http package is extension of the javax.servlet package for http
protocol
The Servlet spec allows you to implement separate Java methods implementing each HTTP
method in your subclass of HttpServlet.
Override the doGet() and/or doPost() method to provide normal servlet functionality.
Override doPut() or doDelete() if you want to implement these methods.
There's no need to override doOptions() or doTrace().
The superclass handles the HEAD method all on its own.
Javax.servlet Package

Provides the contract between the servlet/web application and the


web container
Used for creating protocol independent server applications
Servlet interface defines the core of the entire package
Other interfaces provide additional services to the developer

Contains 12 interfaces
7 interfaces implemented by the package
5 interfaces implemented by the user
Servlet Interfaces

Server implemented interfaces User implemented interfaces


ServletConfig
Servlet
ServletContext
ServletContextListener
ServletRequest
ServletResponse ServletContextAttributeListener

RequestDispatcher SingleThreadModel

FilterChain Filter
FilterConfig
Servlet Classes

Servlet Classes Exception Classes


GenericServlet
ServletException
ServletContextEvent
UnavailableException
ServletContextAttriubuteEvent
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
GenericServlet class
GenericServlet is abstract class that implements servlet interface
Requires implementing the service() method
Servlets normally extend from this class

Methods
LifeCycle Methods
init()
service()
destroy()
Environment Methods
getServletContext()
getInitParameter(…)
getInitParameterNames()
javax.servlet.http

Javax.servlet package provides interfaces and classes to service client


requests in protocol independent manner.
Javax.servlet.http package supports http-specific functions.

Several of the classes are derived from the javax.servlet packaage


Some methods from the javax.servlet package are also used
Contains
8 interfaces
7 classes
HTTP Request

HTTP Request Description


GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is


like GET request with extra info sent with the
request.

HEAD Asks for only the header part of whatever a GET


would return. Just like GET but with no body.

TRACE Asks for the loopback of the request message, for


testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the


requested URL.
DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the


thing at the request URL can respond
HttpServlet Class

Extends the Generic Servlet


Inherits the init() and destroy methods()
Overrides the service() method

Service() method
Signature: Protected void service(HttpServletRequest req, HttpServletResponse res)
Forwards the request to the appropriate method
Developer should not normally override this method

The developer needs to implement the methods corresponding to the


request
doGet(), doPost(), doHead(), doPut()
HttpServletRequest Interface

Extends ServletRequest
Inherited methods from ServletRequest
getParameterNames()
getParameter(String name)
getParameterValues(String name)
getServerName()
getServerPort()
getRequestDispatcher

New methods defined


getCookies()
getHeader()
getPathInfo()
getContextPath()
getQueryString()
. HttpServletRequest Interface, cont’d

Extends ServletResponse
Inherited methods from ServletResponse
getoutputStream()
getWriter(String name)
flushBuffer()
setContentType()

New methods
encodeURL(String url)
encodeRedirectURL(String url)

setDateHeader()
setStatus()
Writing a Servlet

Create a servletclass
extend HttpServlet

Implement the doGet() or doPost() method


Both methods accept two parameters
HttpServletRequest
HttpServletResponse
Obtain parameters from HttpServletRequest Interface using
getParameter(String name)
Obtain the writer from the response object
Process input data and generate output (in html form) and write to the writer
Close the writer
Example 1
Example 1
Login Servlet

import javax.servlet.http.*;
import java.io.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
// Get the parameter from the request
String username = request.getParameter("username");
// Send the response back to the user
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
writer.println("Thank you, " + username + ". You are now logged into the system.");
writer.println("</body></html>");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 1
Login.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
Please enter your username and password
<form action="servlet/niet.servlets.Login" method="POST">
<p><input type="text" name="username" length="40">
<p><input type="password" name="password" length="40">
<p><input type="submit" value="Submit">
</form>
</body>
</html>

73
Example 1
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Login Servlet</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>niet.servlets.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>

74Shweta
Singh
Example 1
Login Deployment

Compiling
• Makefile contains all the scripts for compiling and deployment of the servlet
• Needs to be modified for any give application

Commands
• make shutdown: shuts down the tomcat server
• make clean: cleans up the current setup for the application
• make all: compiles code, creates war file and deploys war file on server
• make startup: starts the server again

Running the servlet
• http://localhost:8080/login/login.html
SendRedirect in servlet

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it
may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it can work inside and
outside the server.
Syntax of sendRedirect() method

public void sendRedirect(String URL)throws IOException;

Eg:

response.sendRedirect("http://www.niet.co.in");
Difference between forward() and
sendRedirect() method

forward() method sendRedirect() method


The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response objects to It always sends a new request.
another servlet.
It can work within the server only. It can be used within and outside the server.
Example: Example: response.sendRedirect("servlet2");
request.getRequestDispacher("servlet2").forward(req
uest,response);
Session Tracking in Servlet

• Session simply means a particular interval of time.

• Session Tracking is a way to maintain state (data) of an user.

• Http protocol is a stateless so we need to maintain state using session tracking


techniques

• Each time user requests to the server, server treats the request as the new request

• So we need to maintain the state of an user to recognize to particular user.


Cookies In Servlet

• A cookie is a small piece of information that is persisted between the multiple client requests.

• The cookie class provides an easy way for servlet to read, create, and manipulate HTTP-
style cookies, which allows servlets to store small amount of data.

• A servlet uses the getCookies() method to retrieve cookies as request.

• The addCookie() method sends a new cookie to the browser


Example

<cookie.html>

<html>
<body>
<center>
<h1>Cookies Example in Java</h1>
<form action=“"http://localhost:8080/cookies/co” method="Post">
First name: <input type="text" name="fname">
Last name: <input type="text" name="lname">
<input type="submit“ value="SUBMIT">
</form>
</center> </body> </html
Cookies Example(cont..)

<AddCookie.java>

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class AddCookie extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{

Shweta Singh ACSAI0612 Advance


81
Java Programming Unit 1
Cookies Example(cont..)

<AddCookie.java>(cont..)

String fname=req.getParameter("fname");
String lname=req.getParameter("lname");

Cookie f=new Cookie("first_name",fname);


Cookie l=new Cookie("last_name",lname);
res.addCookie(f);
res.addCookie(l);

res.sendRedirect("http://localhost:8080/cookies/st”);
}
}

Shweta Singh ACSAI0612 Advance


82
Java Programming Unit 1
Cookies Example(cont..)

<GetCookie.java>
import javax.servlet.*; out.println("<h1>");
import javax.servlet.http.*; Cookie[] c=req.getCookies();
import java.io.*; for(Cookie k:c)
public class GetCookie extends HttpServlet {
{ out.println(k.getValue());
public void doGet(HttpServletRequest }
req,HttpServletResponse res) throws out.println("</h1>");
ServletException,IOException }
{ }
PrintWriter out=res.getWriter();

Shweta Singh ACSAI0612 Advance


83
Java Programming Unit 1
Session Tracking using HTTPSession interface

• The HttpServletRequest interface provides two methods to get the object of


HttpSession

• public HttpSession getSession()

• public HttpSession getSession(boolean create)

84
Example of Session Tracking using HTTPSession interface

<Index.html>

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Shweta Singh ACSAI0612 Advance


85
Java Programming Unit 1
Example of Session Tracking using HTTPSession
interface

<FirstServlet.java>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResp
onse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String s1=request.getParameter("userName");
out.print("Welcome "+s1);

Shweta Singh ACSAI0612 Advance


86
Java Programming Unit 1
Example of Session Tracking using HTTPSession
interface(cont..)

<FirstServlet.java>

HttpSession session=request.getSession();
session.setAttribute(“First",s1);

out.print("<a href='servlet2'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}

Shweta Singh ACSAI0612 Advance


87
Java Programming Unit 1
Example of Session Tracking using HTTPSession
interface(cont..)

<SecondServlet.java>

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServle
tResponse response)
try{
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);

Shweta Singh ACSAI0612 Advance


88
Java Programming Unit 1
Example of Session Tracking using HTTPSession
interface(cont..)

<SecondServlet.java>

String n=(String)session.getAttribute(“First");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}

Shweta Singh ACSAI0612 Advance


89
Java Programming Unit 1
Event and Listener in Servlet

Events are basically occurrence of something. Changing the state of


an object
We can perform some important tasks at the occurrence of these
exceptions, such as counting total and current logged-in users,
creating tables of the database at time of deploying the project,
creating database connection object

Shweta Singh ACSAI0612 Advance


90
Java Programming Unit 1
Event Class in Servlet

ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
HttpSessionEvent
HttpSessionBindingEvent

Shweta Singh ACSAI0612 Advance


91
Java Programming Unit 1
Event Interface in Servlet

ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
Shweta Singh ACSAI0612 Advance
92
Java Programming Unit 1
ServletContextEvent and ServletContextListener

The ServletContextEvent is notified when web application is


deployed on the server

There is only one constructor defined in the ServletContextEvent


class.

The web container creates the instance of ServletContextEvent


after the ServletContext instance.

Shweta Singh ACSAI0612 Advance


93
Java Programming Unit 1
Example of ServletContextEvent and ServletContextListener

index.html

<a href="servlet1">fetch records</a>

Shweta Singh ACSAI0612 Advance


94
Java Programming Unit 1
Example of ServletContextEvent and ServletContextListener(Cont..)

MyListener.java
import javax.servlet.*;
import java.sql.*;

public class MyListener implements ServletContextListener{


public void contextInitialized(ServletContextEvent event) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//storing connection object as an attribute in ServletContext
ServletContext ctx=event.getServletContext();
ctx.setAttribute("mycon", con);

}catch(Exception e){e.printStackTrace();}
}

public void contextDestroyed(ServletContextEvent arg0) {}


Shweta Singh ACSAI0612 Advance
95
Java Programming Unit 1
Example of ServletContextEvent and
ServletContextListener(Cont..)
MyListener.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class FetchData extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try{
//Retrieving connection object from ServletContext object
ServletContext ctx=getServletContext();
Connection con=(Connection)ctx.getAttribute("mycon");

// Shweta Singh ACSAI0612 Advance


96
Java Programming Unit 1
Example of ServletContextEvent and ServletContextListener(Cont..)

retieving data from emp32 table


PreparedStatement ps=con.prepareStatement("select * from
emp32",
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_
UPDATABLE);

ResultSet rs=ps.executeQuery();
while(rs.next()){
out.print("<br>"+rs.getString(1)+" "+rs.getString(2));
}

con.close();
}catch(Exception e){e.printStackTrace();}

out.close();
}
}

Shweta Singh ACSAI0612 Advance


97
Java Programming Unit 1
Previous Topics: Recap

• The previous topic was mainly focused on the concepts of Java Servlet API and its life cycle.

• It was focused on the various types of classes and interfaces

• It was also focused on the concept of redirecting HTTP request

• It was also focused on servlet event and listener classes with its implementation

Shweta Singh ACSAI0612 Advance


98
Java Programming Unit 1
Daily Quiz(cont..)

• Which middleware services are provided by EJB?

A. Security
B. Transaction Management
C. Both A & B
D. None of the above

• What represents a persistent global data from the database?

A. Entity Bean
B. Session Bean
C. Both A & B
D. None of the above

Shweta Singh ACSAI0612 Advance


99
Java Programming Unit 1
Daily Quiz(cont..)

• Which of the following manages a list of database


drivers in JDBC?
A - DriverManager
B - JDBC driver
C - Connection
D - Statement

• Which of the following is true about JDBC architecture?


A - JDBC API layer provides the application-to-
JDBC Manager connection.
B - JDBC Driver API layer supports the JDBC
Manager-to-Driver Connection.
C - Both of the above.
D - None of the above.
Shweta Singh ACSAI0612 Advance
100
Java Programming Unit 1
Daily Quiz

• How constructor can be used for a servlet?


a) Initialization
b) Constructor function
c) Initialization and Constructor function
d) Setup() method
• Can servlet class declare constructor with ServletConfig object as
an argument?
a) True
b) False
• How is the dynamic interception of requests and responses to
transform the information done?
a) servlet container
b) servlet config
c) servlet context
d) servlet filter
Shweta Singh ACSAI0612 Advance
101
Java Programming Unit 1
Daily Quiz(cont..)

• When init() method of servlet gets called?

A - The init() method is called when the servlet is first created.


B - The init() method is called whenever the servlet is invoked.
C - Both of the above.
D - None of the above.

•What is javax.servlet.http.HttpServlet?

A - interface
B - abstract class
C - concreate class
D - None of the above.

Shweta Singh ACSAI0612 Advance


102
Java Programming Unit 1
Daily Quiz(cont..)

• Which of the following code is used to get session in servlet?

A - request.getSession()
B - response.getSession()
C - new Session()
D - None of the above.

• Which of the following code retrieves the request header?

A - Header.getHeaderName(headerName)
B - response.getHeader(headerName)()
C - request.getHeader(headerName)
D - None of the above.

Shweta Singh ACSAI0612 Advance


103
Java Programming Unit 1
Daily Quiz(cont..)

• Which of the following code retrieves the fully qualified name of the client making this
request?
A - request.getRemoteHost()
B - response.getRemoteHost()
C - Header.getRemoteHost()
D - None of the above.

•Which of the following code can be used to send an error response to the client using the
specified status code and clearing the buffer.
A - request.sendError(statusCode)
B - response.sendError(statusCode)
C - header.sendError(statusCode)
D - None of the above.

Shweta Singh ACSAI0612 Advance


104
Java Programming Unit 1
Daily Quiz(cont..)
• Which of the following code is used to get session in servlet?

A - request.getSession()
B - response.getSession()
C - new Session()
D - None of the above.

•Which of the following code is used to get session id of a HTTP Session


object in servlets?

A - session.getSessionId()
B - session.getId()
C - session.getActiveId()
D - None of the above.

Shweta Singh ACSAI0612 Advance


105
Java Programming Unit 1
Daily Quiz(cont..)
•Three methods of Servlet interface init(), service() and destroy()
i) True
ii) False

•Cookie is a piece of information that stored on server ?


i) True
ii) False

• Session is series of request for a single user.


i) True
ii) False

• init() method in servlet life cycle call again and again


i) True
ii) False
Shweta Singh ACSAI0612 Advance
106
Java Programming Unit 1
Daily Quiz(cont..)

•In CGI based application for every request server create a child
process
i) True
ii) False

• Servlet Container is also called Servlet Manager .


i) True
ii) False

Shweta Singh ACSAI0612 Advance


107
Java Programming Unit 1
Weekly Assignment

Discuss the servlet life cycle and its API in details

Write a program to implement handling HTTP post request.

 Write a program to implement cookies in servlet

Write a program that implement PreparedStatement in JDBC.

 Write a program to implement joining two table in JDBC

Shweta Singh ACSAI0612 Advance


108
Java Programming Unit 1
Youtube & NPTEL Video Links and Online Courses Details

https://www.youtube.com/watch?v=utANrHfAh28
https://www.digimat.in/nptel/courses/video/106105191/L01.html
https://www.youtube.com/watch?v=y_YxwyYRJek
https://www.youtube.com/watch?v=0SFVFe6a
https://www.youtube.com/watch?v=ajhWv31oN1k KK8
https://www.youtube.com/watch?v=v5vLuCBv8vg
https://www.youtube.com/watch?v=5ammL5KU4mo

Shweta Singh ACSAI0612 Advance


109
Java Programming Unit 1
Unit 1 MCQ s
1. The JDBC API has always supported persistent storage of objects defined in the Java
programming language through the methods getObject and setObject.

a. True
b. False
2. The ACID properties does not describes the transaction management well.

a.True
b. False
3. The ResultSet.next method is used to move to the next row of the ResultSet, making
it the current row.
a. True
b. False

Shweta Singh ACSAI0612 Advance


110
Java Programming Unit 1
Unit 1 MCQ s(cont..)

4. How many steps are used to connect any java application using JDBC?

a. 5
b. 4
c. 3
d. 6

5. In the following JDBC drivers which is known as fully java driver?


a. Native-API driver
b. Network Protocol driver
c. Thin driver
d. Both B & C

Shweta Singh ACSAI0612 Advance


111
Java Programming Unit 1
Unit 1 MCQ s(cont..)

6. Which models do the JDBC API support for the database access?
a. Two-tier models
b. Three-tier models
c. Both A & B
d. None of the above

7. Which of the following JDBC drivers is known as a partially java driver?

a. JDBC-ODBC bridge driver


b. Native-API driver
c. Network Protocol driver
d. Thin driver

Shweta Singh ACSAI0612 Advance


112
Java Programming Unit 1
Unit 1 MCQ s(cont..)
8. How many types of JDBC drivers are available?

a. 3
b. 4
c. 2
d. 5

9. How many JDBC product components does the Java software


provides?

a. 3
b. 2
c. 4
d. 5

Shweta Singh ACSAI0612 Advance


113
Java Programming Unit 1
Unit 1 MCQ s(cont..)

10. Which services are provided to EJB components by the EJB container?

a. Transaction support
b. Persistence support
c. Naming support
d. All mentioned above

11. Which session bean maintain their state between client invocations but are not
required to maintain their state across server crashes or shutdowns?
a. Stateful Session Bean
b. Stateless Session Bean
c. Singleton Session Bean
d. None of the above

Shweta Singh ACSAI0612 Advance


114
Java Programming Unit 1
Unit 1 MCQ s(cont..)
18. Which of the following is used to call stored procedure?

a.Statement
b.PreparedStatement
c.CallableStatment
d. CalledStatement

19. Which of the following is method of JDBC batch process?


a. setBatch()
b. deleteBatch()
c. removeBatch()
d. addBatch()

Shweta Singh ACSAI0612 Advance


115
Java Programming Unit 1
Unit 1 MCQ s(cont..)

8. Which method is used to send the same request and response objects to another
servlet in RequestDispacher ?

a. forward()
b. sendRedirect()
c. Both A & B
d. None of the above

9. Which packages represent interfaces and classes for servlet API?

a. javax.servlet
b. javax.servlet.http
c. Both A & B
d. None of the above
Shweta Singh ACSAI0612 Advance
116
Java Programming Unit 1
Unit 1 MCQ s(cont..)
10. Which HTTP Request method is non-idempotent

a. GET
b. POST
c. BOTH A & B
d. None of the above

11. Which object is created by the web container at time of


deploying the project?

a. ServletConfig
b. ServletContext
c. Both A & B
d. None of the above

Shweta Singh ACSAI0612 Advance


117
Java Programming Unit 1
Unit 1 MCQ s(cont..)
12. In HTTP Request what asks for the loopback of the request message, for testing or for
troubleshooting?

a. PUT
b. OPTIONS
c. DELETE
d. TRACE

13. Which one of the following scopes does the attribute in servlet is an object that can be set,
get or removed?
a. session scope
b. request scope
c. application scope
d. All mentioned above

Shweta Singh ACSAI0612 Advance


118
Java Programming Unit 1
Glossary Questions
1. The------------interface is used to call stored procedure?
a) Statement
b) PreparedStatement
c) CallableStatment
d) CalledStatement
2. The-----------method is used to rollback a JDBC
transaction?
a) rollback()
b) rollforward()
c) deleteTransaction()
d) RemoveTransaction()

Shweta Singh ACSAI0612 Advance


119
Java Programming Unit 1
Glossary Questions

3. EJB stands for---------------


A - Enterprise J2EE Bean
B - Enterprise Java Bean
C - Enterprise Java oBject
D - Entity Java object

4. --------------interface session bean is used in EJB.


a) EJBRemote
b) EJBHome
c) Remote

Shweta Singh ACSAI0612 Advance


120
Java Programming Unit 1
Glossary Questions
1. The Java __________ specification defines an application
programming interface for communication between the
Web server and the application program.
a) Servlet
b) Server
c) Program

2. The --------------- application servers do not provide built


in support for servlets.
a) Tomcat server
b) Glassfish
c) Jboss

Shweta Singh ACSAI0612 Advance


121
Java Programming Unit 1
Old Question Paper
2019-20
https://drive.google.com/file/d/1eLOPdCx5cPPU08FiaBH3QiQnHTX_9xhk/view

Shweta Singh ACSAI0612 Advance


122
Java Programming Unit 1
Old Question Paper(cont..)

Shweta Singh ACSAI0612 Advance


123
Java Programming Unit 1
Old Question Paper(cont..)
2018-19
https://drive.google.com/file/d/1FsvkCgeo7sf1q4WRx7vh7A1fRNkJ0_2q/view

Shweta Singh ACSAI0612 Advance


124
Java Programming Unit 1
Old Question Paper(cont..)

Shweta Singh ACSAI0612 Advance


125
Java Programming Unit 1
Old Question Paper(cont..)

Shweta Singh ACSAI0612 Advance


126
Java Programming Unit 1
Expected Questions for University Exam
• Discuss various types of driver used in JDBC details
• Write a program to inserting multiple rows in employee table by
using PreparedStatement interface
•Discuss about Servlet API in details descriptions
• Explain the life cycle of servlet in details
• Write a program that implement Session tracking by usin
HTTPSession method.
•Explain the process to handle the exception on your JSP page
•What is purpose to use the web container in servlet.
•Explain the reason to use sendRedirect() method in JSP with the help
of suitable example.

Shweta Singh ACSAI0612 Advance


127
Java Programming Unit 1
References

Bhave, “Programming with Java”, Pearson Education.

Naughton, Schildt, “The Complete Reference JAVA2”, TMH.

Deitel, “Java for programmers”, Pearson Education.

Tanveer Alam, Internet and Java Programming, Khanna Publishing House.

Balagurusamy E, “Programming in JAVA”, TMH

Shweta Singh ACSAI0612 Advance


128
Java Programming Unit 1
Recap of Unit 1
 Discussed Java Database Connectivity in details

Discussed about the parameterized query statement

Design and implent of stored procedure using JDBC

Explain the servlet overview and its architecture

 Design and implementation of HTTP get and post request

 Discussed about various types session handling in servlet

 Discuss about the life cycle of servlet and jsp with their
implementationShweta Singh ACSAI0612 Advance
129
Java Programming Unit 1
Thank You

Shweta Singh ACSAI0612 Advance


130
Java Programming Unit 1

You might also like