[go: up one dir, main page]

0% found this document useful (0 votes)
5 views8 pages

Servlet Notes

Uploaded by

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

Servlet Notes

Uploaded by

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

Servlet: A servlet is a server side java program that is platform independent.

Servlets , written in java,


dynamically extend the functionality of any java enabled web server. Web servers generally cannot talk
to databases. Hence a web server alone cannot dynamically create web page content using data held in
a database table. Even though servlets are written in java their clients may not necessarily be written in
java.
Why servlets?
1. Are loaded into memory once and run from memory thereafter.
2. Are spawned as a thread not as a process.
3. Are a powerful object oriented abstraction of HTTP.
4. Are portable across multiple web services and platforms.
5. Are simple to design and implement.
6. Run within the secure and reliable scope of JVM.
7. Are supported by several web servers.
8. Are robust, secure CGI replacement.

Life Cycle Of Servlet


A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method


The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations
The servlet is normally created when a user first invokes a URL corresponding to the
servlet.
When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST)
and calls doGet, doPost methods as appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse
response)
throws ServletException, IOException {
}
The service () method is called by the container and service method invokes doGet,
doPost methods as internally. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from
the client.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Servlet code
}

The destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −
public void destroy() {
// Finalization code...
}

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the servlet
container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.
Servlet API
Servlet API is composed of two packages:
javax.servlet  not specific to any protocol
javax.servlet.http  specific to only http protocol

javax.servlet
Classes Interfaces
1.GenericServlet 1.Servlet
2.ServletInputStream 2.ServletRequest
3.ServletOutputStream 3.ServletResponse
4.ServletRequestWrapper 4.RequestDispatcher
5.ServletResponseWrapper 5.ServletConfig
6.ServletRequestEvent 6.ServletContext
7.ServletContextEvent 7.SingleThreadModel
8.ServletRequestAttributeEvent 8.Filter
9.ServletContextAttributeEvent 9.FilterConfig
10.ServletException 10.FilterChain
11.UnavailableException 11.ServletRequestListener
12.ServletRequestAttributeListener

javax.servlet.http
Classes Interfaces
1.HttpServlet 1.HttpServletRequest
2.Cookie 2.HttpServletResponse
3.HttpServletRequestWrapper 3.HttpSession
4.HttpServletResponseWrapper 4.HttpSessionListener
5.HttpSessionEvent 5.HttpSessionAttributeListener
6.HttpSessionBindingEvent 6.HttpSessionBindingListener
7.HttpSessionActivationListener

Practice Questions:
1. Create a servlet to read a number provided from HTML and check odd/even.

2. Create a servlet to add two numbers provided from HTML.

3. Create a servlet to read a word/string from HTML and count its no. of characters.

4. Create a servlet to read a number from HTML and display its reverse.

5. Create a servlet to read a number from HTML and find its factorial.

6. Create a servlet that stores cookie in client computer.


7. Create a servlet that reads the cookie stored in client computer.

8. Create a servlet that takes id, name, address, faculty of a student from HTML form and save it to
database.

9. Create a servlet to display the information(id,name,address,faculty) of database table into a HTML


table.

Structure of a Web-Application

Tomcat

WebApps

projectname

WEB-INF JSP HTML

classes lib web.xml

.class files Jar files


(servlet/POJO
class)
How is a servlet (web application) deployed? Explain.
→ A servlet (web application) can be deployed manually or creating a war (web application
archive) file.

1. To manually deploy a servlet we create the hierarchy of folders as above and place the
required files in the respective folders. Then start the server and access the resource.

For eg

a. if project name is “mywebapp”, then to access the index file

http://localhost:8080/mywebapp (/index.html) optional

b. if project name is “mywebapp”, then to access a servlet with url pattern

/welcome

http://localhost:8080/mywebapp/welcome

2. By creating war file

→ War file can be created by using JAVA IDE like Netbeans, eclipse.

In netbeans war file can be created by right clicking on project and

choosing the clean and build option.

In eclipse war file can be created by right clicking the project and

choosing export option.

The war file created is then placed in the “webapps” folder as shown in

figure. And then the server is started which will create the same

hierarchy of folders as shown in the above figure.


ServletConfig and ServletContext objects:

ServletConfig
-->ServletConfig available in javax.servlet package

-->ServletConfig object is one per servlet class

-->Object of ServletConfig will be created during initialization process of the servlet

This config object is public to a particular servlet only

-->Scope: As long as a servlet is executing, ServletConfig object will be available, it will be destroyed
once the servlet execution is completed.

--><init-param> is used in web.xml

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>HelloServlet</servlet-class>

<init-param>

<param-name>adminEmail</param-name>

<param-value>abc@gmail.com</param-value>

</init-param>

</servlet>

-->In servlet we can read the init param using the code

out.println(getServletConfig().getInitParameter("adminEmail"));

ServletContext
-->ServletContext available in javax.servlet package

-->ServletContext object is global to entire web application


-->Object of ServletContext will be created at the time of web application deployment

-->Scope: As long as web application is executing, ServletContext object will be available, and it will be
destroyed once the application is removed from the server.

--><context-param> is used in web.xml

<servlet>

<servlet-name>First</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<context-param>

<param-name>adminEmail</param-name>

<param-value>abc@gmail.com</param-value>

</context-param>

-->In servlet we can read the context param using the code

out.println(getServletContext().getInitParameter("adminEmail"));

You might also like