CMP_514 Unit-2
CMP_514 Unit-2
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.
For more contents, notes, tips and guidelines follow the links
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.
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.
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.
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.
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2
ADVANCE JAVA
ServletContextAttributeEvent
ServletException
UnavailableException
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent
HttpUtils (deprecated now)
QUICK NOTES COURSE CODE: CMP 514 UNIT - 2
ADVANCE JAVA
Container in Servlet
In console based java applications a class which contains main method acts as a
container for other classes.
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
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
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.
3. Multithreading: A container creates a thread for each request, maintains the thread
and finally destroy it whenever its work is finished.
Installation of server
ADVANCE JAVA
Location
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
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).
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
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.
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
ADVANCE JAVA
Example
Example
Example
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
Method Description
Syntax
ADVANCE JAVA
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.
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
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>");
}
}
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
The web container maintains the life cycle of a Servlet instance or object.
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.
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
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.
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
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
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:
ADVANCE JAVA
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 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");
Base name
Extension name
ADVANCE JAVA
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.
Servlet
JSP
Filter
Listeness
Welcome files
Security
Etc....
<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.
While configuring a servlet in web.xml, three names are added for it.
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>
ADVANCE JAVA
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.
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.
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.
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.
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.
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>
If you have the welcome file, you can directory invoke the project as given below:
Example
http://localhost:8888/myproject/
Servlet programming is very simple but you need some basic knowledge for example
interface, abstract class, exception handling.
ADVANCE JAVA
Write a web application to send hello word as response to client using servlet.
FirstServlet.java
import java.io.*;
import javax.servlet.*;
// 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>