0% found this document useful (0 votes)
7 views28 pages

CMP_514 Unit-2

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 28

QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

महत्वाची माहहती

येथे नोट्स के वळ शैक्षहिक हेतूसाठी वापरल्या जात आहेत,


कॉपी करिे ककिं वा कोित्याही परवानगीहशवाय त्याचा
वापर करिे यावर कठोर कारवाई के ली जाईल.
या नोट्स हवनामूल्य आहेत, आम्ही यासाठी शुल्क
आकारत नाही.

पुनरावृत्ती हेतूसाठी ही नोटस आहेत.

Important Information
Notes here are only use for educational purpose, copying or using it without any
permission, will be taken strict action.

This notes are free of cost, we are not charging for this.

This was the quick notes for the revision purpose.

For more contents, notes, tips and guidelines follow the links

Follow Us on Social Media


QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Introduction to Servlet

Servlet is a java program, exist and executes in j2ee servers, used to receive the http
protocol request, process it and send response to client.

Using Servlet, we can collect input from users through web page forms, present
records or another source, and create web pages dynamically.

History of Servlet

The Servlet specification was created by Sun Microsystems, with version 1.0 finalized
in June 1997. The version 2.3, developed under the Java Community Process.

Why we have to use Servlet

Using Servlets, we can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.

Advantages (Features of Servlet)

1) Better performance: Because it creates a thread for each request not process
(like CGI).
2) Portability: Because it uses java language and java is robust language.
3) Robust: Servlet are managed by JVM so no need to worry about memory leak,
garbage collection etc.
4) Secure: Because it uses java language and java is a secure language. Java
have automatic garbage collection mechanism and a lack of pointers protect
the servlets from memory management problems.
5) Inexpensive There are number of free web servers available for personal use
or for commercial purpose. Mostly web server are very costly. So by using free
web server you can reduce project development price.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

6) Extensibility The servlet API is designed in such a way that it can be easily
extensible. Servlets being written in Java, can be extended and polymorphed
into the objects that suits the user requirement.
7) Efficiency Servlets invocation is highly efficient as compared to any CGI
programs.
8) Integration Servlets are tightly integrated with the server. Servlet can use the
server to translate the file paths, check authorization, perform logging and
MIME type mapping etc.
9) Persistent: Servlets remain in memory until explicitly destroyed. This helps in
serving several incoming requests. Servlets establishes connection only once
with the database and can handle several requests on the same database.
10) Server Independent: Servlets are compatible with any web server available
today.
11) Protocol Independent: Servlets can be created to support any protocols like
FTP commands, Telnet sessions, NNTP newsgroups, etc. It also provides
extended support for the functionality of HTTP protocol.
12) Fast: Since servlets are compiled into byte codes, they can execute more
quickly as compared to other scripting languages. The byte code compilation
feature helps servlets to give much better performance. In addition, it also
provides advantage of strong error and type checking.

What is Servlet API?

Servlet API provides Classes and Interface to develop web based applications.

Package

Servlet API contains two java packages are used to develop the servlet programs,
they are:

 javax.servlet
 javax.servlet.http
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

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

javax.servlet.http package contains list of classes and interfaces to define http servlet
programs. This package are used to interact with browser using http protocol. It is only
responsible for http requests.

Interfaces in javax.servlet package

 Servlet
 ServletRequest
 ServletResponse
 RequestDispatcher
 ServletConfig
 ServletContext
 SingleThreadModel
 Filter
 FilterConfig
 FilterChain
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener

Classes in javax.servlet package

 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletRequestWrapper
 ServletResponseWrapper
 ServletRequestEvent
 ServletContextEvent
 ServletRequestAttributeEvent
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

 ServletContextAttributeEvent
 ServletException
 UnavailableException

Interfaces in javax.servlet.http package

 HttpServletRequest
 HttpServletResponse
 HttpSession
 HttpSessionListener
 HttpSessionAttributeListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

 HttpServlet
 Cookie
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpUtils (deprecated now)
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Container in Servlet

Container provides runtime environment for Java2ee (j2ee) applications. A web


container is a predefined application provided by a server, its takes care of Servlet and
JSP.

In console based java applications a class which contains main method acts as a
container for other classes.

Container in Servlet Example

class Vachile
{
void speed()
{
System.out.println("Speed limit is 40 km/hr");
}
}
class Mainclass
{
public static void main(String args[])
{
Vachile v=new Vachile();
v.speed();
}
}

Output

Speed limit is 40 km/hr

Explanation: Here Main class is providing run-time support for vehicle class so main
class is called a container. In GUI based applications a frame acts as a container for
other awt components like button, text field etc.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Operations of Servlet Container

 Life Cycle Management


 Communication Support
 Multithreaded support
 Security

1. Life cycle management: Servlet and JSP are dynamic resources of java based
web application. The Servlet or JSP will run on a server and at server side. A container
will take care about life and death of a Servlet or JSP.
A container will instantiate, Initialize, Service and destroy of a Servlet or JSP. It means
life cycle will be managed by a container.

2. Communication Support: If Servlet or JSP wants to communicate with server than


its need some communication logic like socket programming. Designing
communication logic is increase the burden on programmers, but container act as a
mediator between a server and a Servlet or JSP and provides communication between
them.

3. Multithreading: A container creates a thread for each request, maintains the thread
and finally destroy it whenever its work is finished.

4. Security: A programmer is not required to write security code in a Servlet/JSP. A


container will automatically provide security for a Servlet/JSP.

How to Set Class Path in Servlet

Installation of server

Download tomcat from the following url https://tomcat.apache.org/download-70.cgi


Download tomcat select tomcat installer version(.exe), will get download as exe file,
install into default location than "tomcat home directory" will be.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Location

"C:\program files\apache software foundation\tomcat 6.0"

Hierarchy of Tomcat Server

Below I will give you description about all folder related to Tomcat Server and their
uses.

 bin:\ This sub folder used to start and stop the tomcat server.
 conf:\ This folder is used to configure server port number for this use server.xml
file.
 lib:\ This folder contains "servlet-api.jar" used to set class path for servlet
programming, this is vender specific.jar file for servlet programming.
 webapps:\ This is the web application deployment folder used to deploy web
application by copying web root or for copy you application.

class path

class path variable is set for providing path of all java classes which is used in our
application. All classes related to servlet are available in lib/servlet-api.jar so we set
class path up to lib/servlet-api.jar.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Set Class path in Servlet

Copy Servlet-api.jar file location and set the class path in environment variable.

If your classpath is already set for core java programming, you need to edit classpath
variable. For edit classpath just put ; at end of previous variable and paste new copied
location (without delete previous classpath variable).

In the above image you can see "C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar" path is


already set now you can only put your servlet-api.jar location at the end of this path.
Finally your complete path is;

C:\Program Files\Java\jdk1.6.0\jre\lib\rt.jar ; C:\Program Files\Apache Software


Foundation\Tomcat 7.0\lib\servlet-api.jar.;

Directory Structure of Servlet Application

For creating web application we should follow standard directory structure provided by
sun MicroSystem. Sun MicroSystem has given directory structure to make a web
application server independent.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

According to directory structure

 An application contain root folder with any name.


 Under root folder a sub folder is required with a name WEB-INF.
 Under WEB-INF two sub folder are required classes and lib.

 All jar files placed inside lib folder.

 Under root folder src folder are place for .java files
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

 Under root folder or under WEB-INF any other folders can exits.
 All image, html, .js, jsp, etc files are placed inside root folder
 All .class files placed inside classes folder.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Web.xml in Servlet

It is a web application deployment descriptor file, contains detail description about web
application like configuration of Servlet, Session management, Startup parameters,
Welcome file..etc.

We cannot change the directory or extension name of this web.xml because it is


standard name to recognized by container at run-time.

web.xml is present inside the Web-INF folder.

Web-INF

This is a web application initialization folder to recognized by the web container at run
time then folder name should be Web-INF to deployed the web application
successfully otherwise deployment name unsuccessful.

In side Web-INF folder we put web.xml file, classes folder, lib folder and any user
defined folder.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

How to Create Servlet

According to servlet API we have three ways to creating a servlet class.

 By implementing servlet interface


 By extending GenericServlet class
 By extending HttpServlet class
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

By implementing servlet interface

Example

public class myServlet implements Servlet


.......
.......
}
By extending GenericServlet class

Example

public class myServlet extends GenericServlet


.......
.......
}
By extending HttpServlet class

Example

public class myServlet extends HttpServlet


.......
.......
}

Servlet Interface

It is an interface to define a Servlet, the implementation class of this Servlet should


override all methods of Servlet interface.

Servlet interface needs to be implemented for creating any Servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the Servlet, to
service the requests, and to destroy the Servlet and 2 non-life cycle methods.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Methods of Servlet interface

Method Description

Initializes the Servlet. It is the life cycle


method of Servlet and invoked by the web
public void init(ServletConfig config) container only once.

Provides response for the incoming


public void service(ServletRequest request. It is invoked at each request by
request,ServletResponse response) the web container.

Is invoked only once and indicates that


public void destroy() Servlet is being destroyed.
public ServletConfig getServletConfig() Returns the object of ServletConfig.

returns information about Servlet such as


public String getServletInfo() writer, copyright, version etc.

Example of servlet by implementing Servlet interface

Syntax

public class myServlet implements server


{
....
}
public void destroy()
{
.....
}
public void init(ServletConfig se)
{
.....
}
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

public ServletConfig getServletConfig()


{
.....
}
public String getServiceInfo()
{
....
}
public void service(ServletRequest req, ServletResponse resp)throws IOException,
ServletException
{
....
}

Generic Servlet

Generic Servlet class Implements Servlet, Servlet Config and Serializable Interfaces.
It provides the implementation of all the methods of these Interfaces except the service
method. Generic Servlet class can handle any type of request so it is protocol
Independent. You may create a generic Servlet by inheriting the Generic Servlet class
and providing the Implementation of the service method.

This is a implemented abstract class for Servlet Interface, have the implementation for
all methods of Servlet interface except service method.

Methods of Generic Servlet

All methods of Servlet Interface are inherit in Generic Servlet class because it
Implements Servlet Interface. Following methods are used in Generic Servlet.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Example of Servlet by inheriting the Generic Servlet class

Example

import java.io.*;
import javax.servlet.*;
public class GenericServletDemo extends GenericServlet
{
public void service(ServletRequest req,ServletResponse resp)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=resp.getWriter();
out.print("<html><body>");
out.print("<b>Example of GenericServlet</b>");
out.print("</body></html>");
}
}

HttpServlet Class in Servlet

This is used to define httpServlet, to receive http protocol request and to send http
protocol response to the client.

The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace,
doDelete, doOption etc.

1. doGet
2. doPost
3. doHead
4. doTrace
5. doDelete
6. doOption
7. doPut
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Life Cycle of Servlet

The web container maintains the life cycle of a Servlet instance or object.

1. Loading (Servlet class is loaded)


2. Installation (Servlet instance is created)
3. Initialization (init method is invoked)
4. Service providing (service method is invoked)
5. Destroying (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.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

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:

Syntax

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:

Syntax

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

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:

Syntax public void destroy()


QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Servlet Life Cycle Example

import javax.servlet.*;
import java.io.*;
public class myservlet extends GenericServlet
{
public void init(ServletConfig sc)
{
System.out.println("init executed...");
}
public void service(ServletRequest req, ServletResponse resp)throws IOException,
ServletException
{
System.out.println("service executed...");
PrintWriter out=resp.getWriter();
resp.setContentType("text/html");
out.println("plz observe output on server console window");
}
public void destroy()
{
System.out.println("Distroy executed...");
}}

web.xml

<web-app>
<servlet>
<servlet-name>srv</servlet-name>
<servlet-class>myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>srv</servlet-name>
<url-pattern>/ms</url-pattern>
</servlet-mapping></web-app>
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Content Type in Servlet

Content Type is also known as MIME Type. MIME stand for multipurpose internet
Mail Extension. It is a HTTP header that provides the description about what are you
sending to the browser (like send image, text, video etc.).

This is the format of http protocol to carry the response contains to the client.

Example: Suppose you send html text based file as a response to the client the MIME
type specification is

Syntax

response.setcontentType("text/html");

MIME type have two parts, they are:

 Base name
 Extension name

Base name: It is the generic name of file.

Extension name: It is extension name for specific file type.

The supporting MIME type by http protocol are:

File MIME Type Extension


xml text/xml. .xml.
HTML text/html. .html.
Plaintext File text/plain. .txt.
PDF application/pdf. .pdf.
gif Image image/gif. .gif.
JPEG Image image/jpeg. .jpeg.
PNG Image image/x-png. .png.
MP3 Music File audio/mpeg. .mp3.
MS Word Document application/msword. .doc.
Excel work sheet application/vnd.ms-sheet. .xls.
Power Point Document application/vnd.ms-powerpoint. .ppt.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Servlet Deployment Descriptor Files

It is an xml file which acts as a mediator between a web application developer and a
web container. It is also called Deployment Descriptor Files.

Note: we cannot change the directory or extension name of this web.xml because it
is standard name to recognized by container at run-time.

In web.xml file, we configure the following

 Servlet
 JSP
 Filter
 Listeness
 Welcome files
 Security
 Etc....

To configure a servlet file we need the following two xml tag.

 <Servlet>
 <Serlet-mapping>
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

<servlet>: tag are used for configure the servlet, Within this tag we write Servlet name
and class name.

<Serlet-mapping>: tag are used for map the servlet to a URL.

The structure of web.xml files is already defined by sun MicroSystem. So as a


developer we should follows the structure to develop the configuration of web
resources.

While configuring a servlet in web.xml, three names are added for it.

 Alias name or register name


 Fully qualified class name
 url-pattern

Syntax

<web-app>
<servlet>
<servlet-name>alias name</servlet-name>
<servlet-class>fully qualified class name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>alias name</servlet-name>
<url-pattern>/url pattern</url-pattern>
</servlet-mapping>
</web-app>

<load-on-startup> Element in Servlet

This is a web.xml configuration elements used to configure a servlet to create servlet


object during startup time of the server or application deploy on server. It is also known
as pre initialization of servlet. This element need integer value to configure.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Advantage of load-on-startup element

As we know well, servlet is loaded at first request. That means it consumes more time
at first request. If we specify the load-on-startup in web.xml, servlet will be loaded at
project deployment time or server start. So, it will take less time for responding to first
request.

Passing positive value

If we pass the positive value, the lower integer value servlet will be loaded before the
higher integer value servlet. In other words, container loads the servlets in ascending
integer value. The 0 value will be loaded first then 1, 2, 3 and so on.

Let's try to understand it by the example given below:

web.xml

<web-app>
....

<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.tutorial4us.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>

<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.tutorial4us.SecondServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

...
</web-app>
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

There are defined 2 servlets, both servlets will be loaded at the time of project
deployment or server start. But, servlet1 will be loaded first then servlet2.

Passing negative value

If a negative value is configure then a container ignores this tag and waits for first
request to create an object of a servlet but a container does not throws any exception.

Welcome File Configuration in Servlet

A welcome file is the file that is invoked automatically by the server, if you don't specify
any file name. Welcome file is a default starting page of the website.

The welcome-file-list element of web-app, is used to define a list of welcome files. Its
sub element is welcome-file that is used to define the welcome file.

By default server looks for the welcome file in following order:

1. index.html
2. index.htm
3. index.jsp

Note: If welcome file is not configure and index.html or index.jsp does not exits in an
application then container sends http status 404 message to the browser.

If you have specified welcome-file in web.xml, and all the files index.html, index.htm
and index.jsp exists, priority goes to welcome-file.

If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file
then index.htm and at last index.jsp file.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Let's see the web.xml file that defines the welcome files.

web.xml

Example

<web-app>
....
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
</web-app>

Now, home.html and default.html will be the welcome files.

If you have the welcome file, you can directory invoke the project as given below:

Example

http://localhost:8888/myproject/

Servlet First Program

Servlet programming is very simple but you need some basic knowledge for example
interface, abstract class, exception handling.

Steps to write servlet program

 Define web directory structure


 Define .jsp/.html pages
 Define servlet program, compile into classes folder
 Define web.xml, into WEB-INF folder
 Deploy the web root into web server deployment folder location.
 Start the server
 Open web browser and invoke servlet/.html/.jsp.
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

Write a web application to send hello word as response to client using servlet.

FirstServlet.java

import java.io.*;
import javax.servlet.*;

public class FirstServlet extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse


response)throws IOException, ServletException
{
// get request parameter
// business operation
String resultvalue="<body bgcolor="cyan" text="red"> <h1> hello word</h1></body>";

// prepare response
resp.setContentType("text/html");
printWriter out=resp.getWriter();

// send response
out.print(resultvalue);
out.close();
}
}
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2

ADVANCE JAVA

web.xml

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>

You might also like