0% found this document useful (0 votes)
134 views18 pages

Unit 1

The document discusses Servlets, which are Java programming elements that reside on the server-side and generate dynamic web pages. Servlets provide a standard way to write Java code that runs on servers. The document covers the Servlet API, Servlet interfaces and classes, the Servlet lifecycle including initialization and destruction methods, and how to create and deploy Servlets using annotations or a web deployment descriptor.

Uploaded by

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

Unit 1

The document discusses Servlets, which are Java programming elements that reside on the server-side and generate dynamic web pages. Servlets provide a standard way to write Java code that runs on servers. The document covers the Servlet API, Servlet interfaces and classes, the Servlet lifecycle including initialization and destruction methods, and how to create and deploy Servlets using annotations or a web deployment descriptor.

Uploaded by

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

V2V Classes Enterprise Java Notes Unit -1

Servlet

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

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was many disadvantages of this technology. We have discussed these
disadvantages below.

There are many interfaces and classes in the servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse etc.

What is a Servlet?

Servlet can be described in many ways, depending on the context.

 Servlet is a technology i.e. used to create web application.


 Servlet is an API that provides many interfaces and classes including documentations.
 Servlet is an interface that must be implemented for creating any servlet.
 Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.
 Servlet is a web component that is deployed on the server to create dynamic web page
V2V Classes Enterprise Java Notes Unit -1
Advantages of Servlet:

1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language..

Servlet API

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.

Let's see what are the interfaces of javax.servlet package.

Interfaces in javax.servlet package

There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
V2V Classes Enterprise Java Notes Unit -1
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package

There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Life Cycle of a Servlet (Servlet Life Cycle)

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
V2V Classes Enterprise Java Notes Unit -1
4. service method is invoked.
5. destroy method is invoked

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.
V2V Classes Enterprise Java Notes Unit -1
2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet
instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init
method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet
interface. Syntax of the init method is given below:

1. public void init(ServletConfig config) throws ServletException  

4) service method is invoked

The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only
once. The syntax of the service method of the Servlet interface is given below:

1. public void service(ServletRequest request, ServletResponse response)   
2.   throws ServletException, IOException  

The doGet() Method:

This method process normal request to URL form as shown below:

3. public void doGet(HttpServletRequest request, HttpServletResponse response)   

  throws ServletException, IOException  

The doPost() Method:

A POST request results from an html form that specially lists POST as the METHOD and it
should be handled by doPost() method.

4. public void doPost(HttpServletRequest request, HttpServletResponse response)   

  throws ServletException, IOException  
V2V Classes Enterprise Java Notes Unit -1
5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory, thread
etc. The syntax of the destroy method of the Servlet interface is given below:

1. public void destroy()  

Steps to Creating a Simple Servlet:

Following are the steps to create web application using servlet in Netbeans.

1. Go to the file menu


2. Select new project
3. Select categories as java web
4. Provide project name and click on next button
5. Select framework which you want to work and click on finish button.

Servlet Life Cycle Code:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/ServletLifeCycle"})
public class ServletLifeCycle extends HttpServlet
{

public ServletLifeCycle()
{
System.out.println("Am from default constructor");
}

public void init(ServletConfig config)


{
System.out.println("Am from Init method...!");
}

public void doGet(HttpServletRequest req,HttpServletResponse res)throws


ServletException,IOException
{
V2V Classes Enterprise Java Notes Unit -1
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
pw.println("I am from doGet method");
pw.close();
}

public void destroy()


{
System.out.println("Am from Destroy methods");
}
}

Deployment Descriptor:

Web.xml file:

<servlet>
  <servlet-name>watermelon</servlet-name>
  <servlet-class>myservlets.watermelon</servlet-class>
</servlet>

<servlet>
  <servlet-name>garden</servlet-name>
  <servlet-class>myservlets.garden</servlet-class>
</servlet>

<servlet>
  <servlet-name>list</servlet-name>
  <servlet-class>myservlets.list</servlet-class>
</servlet>

<servlet>
  <servlet-name>kiwi</servlet-name>
  <servlet-class>myservlets.kiwi</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>watermelon</servlet-name>
  <url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>

<servlet-mapping>
  <servlet-name>garden</servlet-name>
  <url-pattern>/seeds/*</url-pattern>
</servlet-mapping>
V2V Classes Enterprise Java Notes Unit -1
<servlet-mapping>
  <servlet-name>list</servlet-name>
  <url-pattern>/seedlist</url-pattern>
</servlet-mapping>

<servlet-mapping>
  <servlet-name>kiwi</servlet-name>
  <url-pattern>*.abc</url-pattern>
</servlet-mapping>
Servlet annotation:

Annotation represents the meta data. If you use annotation , deployment descriptor(web.xml file)
is not required .

package net.javatutorial.tutorials;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "simpleServlet", urlPatterns = { "/hello" })

public class ServletWithAnnotations extends HttpServlet {

private static final long serialVersionUID = -3462096228274971485L;

@Override

protected void doGet(HttpServletRequest reqest, HttpServletResponse response)

throws ServletException, IOException {

response.getWriter().println("Hello World!");

}
 
V2V Classes Enterprise Java Notes Unit -1
JDBC

What is JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of
executables, such as −

 Java Applications
 Java Applets
 Java Servlets
 Java ServerPages (JSPs)
 Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.

Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.
V2V Classes Enterprise Java Notes Unit -1
Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers
(written in Java language).

What is API

API (Application programming interface) is a document that contains description of all the
features of a product or software. It represents classes and interfaces that software programs can
follow to communicate with each other. An API can be created for applications, libraries,
operating systems, etc

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −

 JDBC API: This provides the application-to-JDBC Manager connection.


 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
V2V Classes Enterprise Java Notes Unit -1

Common JDBC Components

The JDBC API provides the following interfaces and classes −

 DriverManager: This class manages a list of database drivers. Matches connection


requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
 Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
 Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
 Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
 ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
 SQLException: This class handles any errors that occur in a database application.
V2V Classes Enterprise Java Notes Unit -1
Types of Drivers

What is JDBC Driver?

JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.

For example, using JDBC drivers enable you to open database connections and to interact with it
by sending SQL or database commands then receiving results with Java.

The Java.sql package that ships with JDK, contains various classes with their behaviours defined
and their actual implementaions are done in third-party drivers. Third party vendors implements
the java.sql.Driver interface in their database driver.

JDBC Drivers Types

JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates. Sun has divided the implementation types into four
categories, Types 1, 2, 3, and 4, which is explained below −

Type 1: JDBC-ODBC Bridge Driver

In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.

When Java first came out, this was a useful driver because most databases only supported ODBC
access but now this type of driver is recommended only for experimental use or when no other
alternative is available.
V2V Classes Enterprise Java Notes Unit -1

The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.

Type 2: JDBC-Native API

In a Type 2 driver, JDBC API calls are converted into native C/C++ API calls, which are unique
to the database. These drivers are typically provided by the database vendors and used in the
same manner as the JDBC-ODBC Bridge. The vendor-specific driver must be installed on each
client machine.

If we change the Database, we have to change the native API, as it is specific to a database and
they are mostly obsolete now, but you may realize some speed increase with a Type 2 driver,
because it eliminates ODBC's overhead.
V2V Classes Enterprise Java Notes Unit -1

The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.

Type 3: JDBC-Net pure Java

In a Type 3 driver, a three-tier approach is used to access databases. The JDBC clients use
standard network sockets to communicate with a middleware application server. The socket
information is then translated by the middleware application server into the call format required
by the DBMS, and forwarded to the database server.

This kind of driver is extremely flexible, since it requires no code installed on the client and a
single driver can actually provide access to multiple databases.
V2V Classes Enterprise Java Notes Unit -1
You can think of the application server as a JDBC "proxy," meaning that it makes calls for the
client application. As a result, you need some knowledge of the application server's configuration
in order to effectively use this driver type.

Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.

Type 4: 100% Pure Java

In a Type 4 driver, a pure Java-based driver communicates directly with the vendor's database
through socket connection. This is the highest performance driver available for the database and
is usually provided by the vendor itself.

This kind of driver is extremely flexible, you don't need to install special software on the client
or server. Further, these drivers can be downloaded dynamically.

MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.

Which Driver should be Used?


If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver, and is typically used for
development and testing purposes only.
V2V Classes Enterprise Java Notes Unit -1
Database Connectivity Steps:

5 Steps to connect to the database in java

There are 5 steps to connect any java application with the database in java using JDBC. They are
as follows:

 Register the driver class


 Creating connection
 Creating statement
 Executing queries
 Closing connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException  

Example to register the OracleDriver class

1. Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

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

Example to establish connection with the Oracle database

1. Connection con=DriverManager.getConnection(  
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");  
V2V Classes Enterprise Java Notes Unit -1

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

1. public Statement createStatement()throws SQLException  

Example to create the statement object

1. Statement stmt=con.createStatement();  

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

1. public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query

1. ResultSet rs=stmt.executeQuery("select * from emp");  
2.   
3. while(rs.next()){  
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
5. }  

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

1. public void close()throws SQLException  
V2V Classes Enterprise Java Notes Unit -1
Example to close connection

1. con.close();  

You might also like