Transcript Servlets
Servlets
By
B. Venkateswarlu
M.Tech
Assoc Prof IT(Dept)
Newton’s Institute of Engineering
Servlets
Servlets are java objects which are capable of
extending functionality of web server
Servlets are server side Java programs
Servlets are Java classes that process the request
dynamically
Servlets are used to process the HTTP requests and
generate the HTML response.
A servlet is a small Java program that runs within a Web server.
Servlets receive and respond to requests from Web clients, usually
across HTTP, the HyperText Transfer Protocol. Servlet is an
opposite of applet as a server-side applet. Applet is an application
running on client while servlet is running on server.
Request
Servlet
Client
Response
Server
Servlet Life Cycle
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
1. init()-The servlet is initialized by calling the init ()
method
2. service()-The servlet calls service() method to
process a client's request
3. destroy()-The servlet is terminated by calling the
destroy() method
Finally, servlet is garbage collected by the garbage
collector of the JVM
Servlet Lifecycle
Server loads Servlets
- run init method
No Concurrency Issue
Server runs init only once, not per request
Servlets Accept Request from
Clients and return Data back
- run service method
service must be thread-safe
- multiple service method at a time
if that is impossible, servlet must
implement SingleThreadModel interface
Server removes Servlets
- run destroy method
Server reloads Servlets
- run init method
destroy must be thread-safe
- when server runs destroy, other threads
might be accessing shared resources
Init():
The init method is designed to be called only once
It is called when the servlet is first created, and not
called again for each user request.
The init() method simply creates or loads some data
that will be used throughout the life of the servlet
Look like this:
public void init() throws ServletException
{
// Initialization code...
}
Service():
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.
public void service(ServletRequest request,
ServletResponse response) throws ServletException,
IOException
{-----}
Destroy():
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
public void destroy() { -- // Finalization code..--- }
Development of a Web application
Step1:
Create a directory to place everything related to
the web application. This directory can be called as
“Web Root” or “Document Root”
ServletApp
Ex: C:\ServletApp
Step 2:
Under Web Root create a directory with the name
WEB-INF
ServletApp
Ex: C:\ServletApp\WEB-INF
WEB-INF
Step 3:
Under WEB-INF create two directories
a)classes
Root Directory or
ServletApp
b)lib
Webroot
WEB-INF
classes
Used to place
Servlet .class files
lib
Used to place jar files
Create a Servlet Class as follows
Step4:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse response)throws
IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter( );
out.println("<html>");
out.println("<head>");
out.println("<title>WelcomeServlet</title>");
out.println("</head>");
out.println("<body bgcolor="pink">");
out.println("<h1>HelloWorld</h1>");
out.println("</body>");
out.println("</html>");
out.close( );
}
}
Step5:
Set the CLASSPATH with servlet-api.jar file and compile
created Servlet class
C:\>ServletApp>WEB-INF>classes>set
CLASSPATH=%CLASSPATH%; C:\Program
Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar;.
C:\>ServletApp>WEB-INF>classes>javac HelloServlet.java
Step6:Create web.xml file under WEB-INF directory
web.xml
<web-app>
<servlet>
<servlet-name>some</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>some</servlet-name>
<url-patteren>/firstservlet</url-patteren>
</servlet-mapping>
</web-app>
OUTPUT:
Hello World
Developed Application
.
ServletApp
WEB-INF
classes
lib
web.xml
HelloServlet.java
HelloServlet.class
*.jar
Deployment
copy the developed
web application and place in
Tomcat Web Server’s webapps
directory
Running
Start the Server
Goto
All Programs->
Apache Tomcat 6.0->
Configure Tomcat
Open a browser and
call the Servlet using following URL
http://localhost:8080/ServletApp/firstservlet
http://localhost:8080/ServletApp/firstservlet
Servlet program for displaying current date.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class DateServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse
response)throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter( );
out.println("<html>");
out.println("<body>");
Date d=new Date();
out.println("Today Date is"+d);
out.println("</body>");
out.println("</html>");
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>two</servlet-name>
<servlet-class>DateServlet</servletclass>
</servlet>
<servlet-mapping>
<servlet-name>two</servlet-name>
<url-patteren>/second</url-patteren>
</servlet-mapping>
Output:
</web-app>
Today Date is
Mon Feb 27 09:15:36 PDT 2012
Servlet API
The Servlet API consists of classes and
interfaces needed to build servlets.
These classes and interfaces come in two
packages
1. javax.servlet
2. javax.servlet.http
Javax.servlet package
It contains number of interfaces and classes that
establish the framework.
Interfaces
Classes
1.Servlet
1.GenericServlet
2.ServletConfig
2.ServletInputStream
3.ServletContext
3.ServletOutputStream
4.ServletRequest
4.ServletException
5.ServletResponse
5.UnavailableException
Here Servlet interface and GenericServlet class are
important.
Servlet Development
javax.servlet.Servlet
implements
javax.servlet.GenericServlet
(Abstract)
void init(ServletConfig)
void destroy()
void service(ServletRequest, ServletResponse)
ServletConfig getServletConfig()
String getServletInfo()
init(ServletConfig)
init()
…….
Does not implement service() method
extends
javax.servlet.http.HttpServlet
(Abstract)
doxxx(HttpServletRequest, HttpServletResponse)
protected service(
HttpServletRequest, HttpServletResponse)
public service(ServletRequest, ServletResponse)
There are 3 ways to develop a servlet
1. Take a java class implementing javax.servlet.Servlet
interface and provide implementation for all 5 methods.
Ex: public class MyServlet implements Servlet {-------}
2. Take a java class extending form
javax.servlet.GenericServlet and provide implementation
for service() method
Ex:public class MyServlet extends GenericServlet{----}
3.Take a java class extending from
javax.servlet.http.HttpServlet and Override either one of
the service mehtod or one of the doXXX() methods.
Ex: public class MyServlet extends HttpServlet {-------}
Javax.servlet.http package
It contains number of interfaces and classes that are
commonly used by servlet developers.
Interfaces
1.HttpServletRequest
2.HttpServletResponse
3.HttpSession
4.HttpSessionBindingListener
Classes
1.Cookie
2.HttpServlet
3.HttpSessionEvent
4.HttpSessionBindingEvent
Servlet program for reading data from html form.
(Verifying Whether the user is eligible to vote or not)
index.html
<html>
<head>
<title>Homepage</title>
</head>
<body bgcolor="skyblue">
<form name="myform" method=get action="/first">
FirstName<input type=text name=fname><br>
LastName<input type=text name=lname><br>
Age<input type=text name=age><br>
First Name
<input type=submit value=verify>
<input type=reset value=cancel>
</form>
Last Name
</body>
</html>
Age
Venkat
Bombotula
27
Verify
Cancel
Servlet Program
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class VoteServlet extends HttpServlet
{
public void service(HttpServletRequest request, HttpServletResponse
response)throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<body>");
String fn=request.getParameter("fname");
String ln=request.getParameter("lname");
int ag=Integer.parseInt(request.getParameter(“age"));
if(ag>=18)
out.println(“Mr/Ms”+fn+” “+ln+”is eligible to vote”);
else
out.println(“Mr/Ms”+fn+” “+ln+”is not eligible to vote”);
out.println("</body>");
out.println("</html>");
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>some</servlet-name>
<servlet-class>VoteServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>some</servlet-name>
<url-patteren>/first</url-patteren>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Output:
Mr/Ms Venkat Bombotula is eligble to vote
ServletConfig Object:
One per Servlet Object
It will be created by web server when Servlet object is
created and will be destroyed by web server when
Servlet object is destroyed.
Useful to gather init-parameters(Local variables) of a
Servlet availabe in web.xml
Userful to get information of a perticular Servlet
Different ways to get access to ServletConfig object
1. public class TestServlet extends HttpServlet
{
public void init(ServletConfig sc)
{
---
//Use sc object here
---
}
}
2. public class TestServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)
{
ServletConfig sc=getServletConfig();
---
//Use sc object here
- --
}
}
Getting Initialization parameters(Local variables)
from web.xml to servlet
<web-app>
<servlet>
<servlet-name>in</servlet-name>
<servlet-class>InitServlet</servlet-class>
<init-param>
<param-name>SNo</param-name>
<param-value>09A11A1227</param-value>
</init-param>
<init-param>
<param-name>SName</param-name>
<param-value>Sai Ram</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>in</servlet-name>
<url-pattern>/init</url-pattern>
</servlet-mapping>
</web-app>
Getting Initialization parameters(Local variables)
from web.xml to servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InitServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
ServletConfig cg=getServletConfig();
/*
String sn=cg.getInitParameter("SNO");
String sna=cg.getInitParameter("SNAME");
out.println(sn+" "+sna);
*/
Enumeration e=cg.getInitParameterNames();
while(e.hasMoreElements())
{
String name=(String)e.nextElement();
String no=cg.getInitParameter(name);
out.println(name+" "+no+"<br>");
}
}
}
OUTPUT: O9A11A1227
Sai Ram
ServletContext:
One per web application
Web server creates this object when application is
deployed
Web server destroys this object when web application
is undeployed or reloaded or stopped
Useful to gather context parameters or global unic
parameters from web.xml
Userful to get information of entire application
Different ways to get access to ServletContext object
1. public class TestServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response
{
---
ServletConfig sc=getServletConfig();
ServletContext cg=sc.getServletContext();
//Use cg object here
---
}
}
2. public class TestServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)
{
ServletContext cg=getServletContext();
---
//Use cg object here
- --
}
}
Getting Context-parameters(Global variables)
from web.xml to servlet
<web-app>
<servlet>
<servlet-name>ctx</servlet-name>
<servlet-class>ContextServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ctx</servlet-name>
<url-pattern>/global</url-pattern>
</servlet-mapping>
<context-param>
<param-name>Driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>URL</param-name>
<param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>nie123</param-value>
</context-param>
</web-app>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ContextServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp)
throws ServletException,IOException
{
try
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
ServletContext sc=getServletContext();
String driver=sc.getInitParameter("Driver");
String url=sc.getInitParameter("URL");
String user=sc.getInitParameter("username");
String pass=sc.getInitParameter("password");
//load driver
Class.forName(driver);
//connect with db
Connection con=DriverManager.getConnection(url,user,pass);
out.println("Connected With DB using ContextParameters");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
OUTPUT:
Connected With DB using
ContextParameters