5-8 Lect Servlet1
5-8 Lect Servlet1
Bill
------
Exit ------
He goes to the
counter...
A customer enters Food
the restaurant Counter
Order
Collects the
Pays the bill
items and leaves
He places the order
A Typical Restaurant
The restaurant may need to be expanded
Server-side
Java Servlets
Java Scripts (SSJS)
PHP
How we see our web application
You use HTML
to say what a
web page is
<script> request
Var request
Function
{
}
</script> response
User Servlet
Servlet classes and interfaces
HTTP Servlet
Skeleton code for a Servlet
public class myServlet extends HttpServlet
{
public void init()
{
…..//initialization code
}
public void service()
{
……………..
…….. // Code
……………..
}
public void destroy()
{
……………….
…..// freeing resources
}}
Sample servlet program
//Program : myServlet.java Compiler : JDK 1.2
import java.io.*;
import javax.servlet.*;
public class myServlet extends GenericServlet {
public void service(ServletRequest req, ServletResponse
res) throws ServletException, IOException {
res.setContentType("Text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>My First Servlet
</TITLE></HEAD>" );
out.println("<BODY>");
out.println("Hello, " + name);
out.println("</BODY></HTML>");
}}
Servlet Life Cycle and API
Basics
Session Objectives
Describe Servlet Life Cycle
Garbage
Collection
Servlet Life Cycle
Servlet life-cycle methods
Detailed Servlet life cycle - I
The steps in the servlet lifecycle can be explained as
follows
service method
Servlet life-cycle methods
Invoked by container
Container controls life cycle of a servlet
Defined in
javax.servlet.GenericServlet class or
init()
destroy()
service() - this is an abstract method
javax.servlet.http.HttpServlet class
doGet(), doPost(), doXxx()
service() - implementation
init()
Invoked once when the servlet is first instantiated
Perform any set-up in this method
Setting up a database connection
destroy()
Invoked before servlet instance is removed
Perform any clean-up
Closing a previously created database connection
Extending Servlet interface
(example)
/* Program : HelloWorld.java JDK 1.2 JSDK 2.0
//Import Servlet Libraries
//Import Java Libraries
public class HelloWorld implements Servlet
{
static int numreq = 0 ;
private ServletConfig config;
public void init (ServletConfig param_config)
throws ServletException {
this.config = param_config;
}
public ServletConfig getServletConfig() {
return config;
}
Extending Servlet interface
(example)
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter(); // opening an output stream
out.println("<HTML>"); //Writing to an output stream
out.println(“<HEAD><TITLE>Hello World Sample Servlet</TITLE></HEAD>");
out.println("<BODY><CENTER><H1>Hello World!</H1></CENTER>");
numreq++; //increments the hit counter
out.println("<P>This servlet is requested " + numreq + "times");
………………………………….//Close tags
out.close(); // Always close the output stream
}
public String getServletInfo(){
return("Servlet returing Hello World to the client browser"); }
public void destroy() { // servlet is being unloaded }
}
Servlet Interface - I
init() :
public void init(ServletConfig config)
throws ServletException
service():
Accepts two parameters
Request object that implements
ServletRequest or HttpServletRequest
Response object which implements
ServletResponse or HttpServletResponse.
Servlet interface - II
destroy()
public void destroy()
Used to clean up any resources and is called only
when all services are complete
getServletConfig()
public abstract ServletConfig getServletConfig()
GenericServlet class - I
Object
Servlet interface
implements
GenericServlet ServletConfig
Class interface
Serializable
MyWorld interface
Servlet
GenericServlet class - II
init()
destroy()
getServletConfig()
getServletContext()
log()
We need not implement any of these methods as they
are already included within the GenericServlet class
Extending GenericServlet
(example)
public class MyWorld extends GenericServlet
{
static int numreq=0;
public String getServletInfo() { ……………. }
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
PrintWriter out = res.getWriter(); // opening an output
…………………….. //set content type
………………… ….//Writing to an output stream
out.println("<CENTER><H1>My Servlet World!</H1></CENTER>");
numreq++; //increments the hit counter
out.println("<P>This servlet is requested " +numreq+"times");
……………….. }
}
Using getInitParam( ) method
public class InitParam extends GenericServlet
{
int maxRows;
int count;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
try
{
count = Integer.parseInt(getInitParameter("initial"));
}
catch (NumberFormatException e)
{
count =0;
}
}
}
Using getInitParam( ) method
public void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException
{
………………………. // opening an output stream and set content
//Writing to an output stream
…………………………
out.println("<CENTER><H1>Hello World!</H1></CENTER>");
count++;
out.println("Count : " + count + "\n");
out.close(); // Always close the output stream
}
HttpServlet class
Object
Servlet interface
implements
GenericServlet ServletConfig
Class interface
HTTPServlet Serializable
Class interface
implements
User Defined
Servlet
HttpServlet class - I
Service()
doGet() doOptions()
doPost() doTrace()
doPut() doDelete()
HTTP response
BROWSER SERVER
GET /POST
GET
BROWSER SERVER
POST
Generates an HTTP
response
HTTP/1.1 200 ok
browser
Reading All Parameters
First the servlet looks at all the names by the
getParameterNames method of HttpServletRequest.
User clicks a link that has a URL to a servlet instead of a static page
browser
container request
2 servlet
response
The container sees that the request is for servlet, so the container creates two object
1) HttpServletRequest1 2) HttpServletResponse
servlet
browser request
container
3 thread
response
The container finds the correct servlet based on the URL in the request, creates or allocate a thread
for that request, and passes the request and response object to the servlet thread.
servlet
browser
container
4 service
The container calls the servlet’s service () method. Depending on the type of request. The
service( ) method calls either the doGet() or doPost( ) method.
servlet
browser container
5 service
response
doGet( )
The doGet() method generated the dynamic page and stuffs the page into response object.
Container still has a reference to a response object
servlet
browser HTML page container
6
response
request service
The thread compltes, the container converts the response object into an HTTP response, Send it back to the
client, then delete the request and response object
Creating to Database
SQL Server Connectivity
STEP1: Firstly ensure that the MySQL Database server is running on
your machine. The MySQL Server node in the Service indicates
whether the MySQL Database Server is connected. Otherwise right
click and connect it.
Or when right click the client table and choose view data, the
created table displays: