0% found this document useful (0 votes)
41 views89 pages

5-8 Lect Servlet1

Uploaded by

Swarnali Sarkar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views89 pages

5-8 Lect Servlet1

Uploaded by

Swarnali Sarkar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 89

Session 1

Web Applications and


Servlets
Session Objectives
 Explain Web based application architecture
 Explain the working of a webserver
 Describe the basics of HTTP
 List and compare various server side
technologies
 Describe the advantages of using servlets
 Explore a servlet’s basic structure
A Day In A Typical Restaurant
A customer enters A Waiter Accept the order
the restaurant and then serves food

Bill
------
Exit ------

The customer Then the money


leaves the The customer asks
is paid
restaurant for the bill

This system runs smoothly runs with a few customer


An example - McDonalds a Chain of Restaurants
Back end Chef

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

Greater Investment This can be a solution but


incase customers want to
Increased cost place orders from a remote
location, then the web can
come to rescue

Places order Passes it


Client Waiter Chef
Serves Sends back the
processed order
The Web Based Solution - New way of doing
business - E-commerce

Places order Web Server


HTTP request
receives request
(Waiter)

Information sent back to


Servlets act
client as an HTTP response
as Chefs
Dish
Client Browser Ready

Items are Present


Checks the
restaurant
database Requests for Items
The Web Application Architecture
Web browser : Connects to a ‘Web Server’ and interprets a set of HTML
tags within a page to display the page on the screen.
Web
Web Server
Browser Request Server Script – a
Web Data Server side
Assembling program in Servlet
Page
Response

Presentation Layer Application Layer


(1st Tier) (2nd Tier)
Web page: A text file containing text along with a set of HTML Data Stores
tags.
A web server responds to a web browser’s request for a page and
sends it to the web browser through the Internet Database Layer
(3rd Tier)
Various Server side Technologies
Server side Technologies

Common Gateway Proprietary Web server


Interface(CGI) API’s (ISAPI, NSAPI)

 Server-side
Java Servlets
Java Scripts (SSJS)

Java Server Active Server


Pages (JSP) Pages (ASP)

PHP
How we see our web application
You use HTML
to say what a
web page is

<script> request
Var request
Function
{

}
</script> response

… and css to say


how the page Web server
should look
Web Server
 Server can support multiple concurrent
services
 The Java Web Server is an instance of the
JVM
 It may start several services such as the
HTTP service, Administrative service and
Web Proxy Service
Servlets-defined
 Java™ objects which are based on
servlet framework and APIs and extend
the functionality of a HTTP server.
 Mapped to URLs and managed by
container with a simple architecture
 Available and running on all major web
servers and app servers
 Platform and server independent
Advantages of Servlets
Advantages

Loaded in the same Durable objects. Remain


process space as the in memory until
web server destroyed explicitly

More secure and almost Completely protocol


crash proof independent

Faster than common


scripting languages
Working of Servlet
Request for
Loading
FILE Servlet
HTML Page
WEB HTTP

BROWSER HTML POST Services HTML Files


Invoker Servlet

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

 Work with Servlet APIs

 Handle Servlet exceptions

 Develop Servlets for gathering and


sending HTML form data
Servlet Life Cycle
Servlet
Class Instantiation and
Loading Initialization
init() method
Repetitive
Process
Allocating Client
Process client request to Servlet
request
Destroying Servlet service()
Destroy() method method

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

 Server loads servlet


 Server creates one or more instances of the servlet
class
 Server calls the init() method of each servlet
instance
 Server allocates request to the thread and calls the

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()

The service method calls one of the above methods


Syntax : protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
HttpServlet class - II
 doGet()
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
 doHead()
protected void doHead(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
 doPost()
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
Simple Servlet Generating Plain
Text
Simple Servlet Generating Plain
Text
A Servlet that Generates HTML
 Most servlets are used to generate HTML rather than
plain text.
 To build HTML, you need to :

Tell the browser that you’re sending back HTML,and

Modify the println statements to build a legal Web
page

To tell the browser that you’re sending HTML, you need
to set the HTTP Content-Type response
header.
A Servlet that Generates HTML
 !The way to designate HTML is with a typeof
text/html, so the code would be:
 response.setContentType("text/html");
 Servlets can also create and send other document
types like:

Custom images, using a content-type of image/gif.
 Excel Spread sheets, using content type of
application/vnd.ms-excel.
A Servlet that Generates HTML
A Servlet that Generates HTML
Handling the Client Request
 A query data is known as form data (or query data).
 Form data can be attached to the end of the URL after
a question mark, for GET requests, or sent to the
server on a separate line, for POST requests.
 HTTP is another network protocol that has web
specific feature but it dependes on TCP/IP to get
complete request & response from one place to
another.

HTTP Protocol
 HTTP runs on top of TCP/IP protocol.
 HTTP is another network protocol that has web
specific feature but it depends on TCP/IP to get
complete request & response from one place to
another.
HTTP request

HTTP response

BROWSER SERVER
GET /POST
GET

Browser sends an HTTP GET to


the server, asking the server to
GET the page

BROWSER SERVER

POST

Browser sends an HTTP POST to


the server, giving the server what
user typed into the form.
GET / POST
 GET is a simple request. POST can send
user data.
 POST is a more powerful request. IT’s
like a GET plus plus. With POST, you
can request something and at same
time send form data to the server.
Reading Form Data from Servlets
 Use getParameter method of the
HttpServletRequest, supplying the casesensitive
parameter name as an argument.
 This method can be used in the same form for both GET
and POST requests.
 The method returns a String corresponding to the URL-
decoded value of the first occurrence of that parameter
name.
 An empty String is returned if the parameter exists
but has no value, and null is returned if there is no such
parameter.
Reading Form Data from Servlets
 If the parameter could have more than one value,
use getParameterValues.
 It returns an array of strings.
 The return value of getParameterValues is null
for nonexistent parameter names and is a one-
element array when the parameter has only a single
value.
 Note: Parameter names are case-sensitive.
A Sample FORM using GET
A Sample FORM using GET
A FORM Based Servlet: Get
A Sample FORM using GET
Result
Browser creates an HTML
GET request
<html> Get/TEST1/A.HTML
<head>
</head> The HTTP GET is sent to
<Body> the server
</body
</HTML>

Browser renders the Server finds the page


HTML

Generates an HTTP
response
HTTP/1.1 200 ok

HTTP response is sent to


the browser

browser
Reading All Parameters
 First the servlet looks at all the names by the
getParameterNames method of HttpServletRequest.

 This method returns an Enumeration that contains the


parameter names in an unspecified order.

 Loop through the enumeration and for each parameter


name, obtain its value using getParameterValues, that
yield an array of strings.
Reading All Parameters: Servlet
Reading All Parameters: Servlet
Reading All Parameters: Servlet
Reading All Parameters: HTML
Reading All Parameters: HTML
Filtering Strings for HTML-Specific
Characters
 When a servlet wants to generate HTML that will contain
characters like < or >, it simply uses &lt; or &gt;, the
standard HTML character entities.

 Similarly, if a servlet wants a double quote or an


ampersand to appear inside an HTML attribute value, it
uses &quot; or &amp;.

 Else, the HTML code would be malformed.


Code for filtering
Code for filtering
Filtering Strings for HTML-Specific
Characters
 Another example could be when we would
like to embed some code into a servlet.
 Suppose we would like to display the
following code:
 if (a<b) {
 doThis();
 } else {
 doThat();
 }
HTTP Request Headers
 HTTP information is sent from the browser
to the server in the form of request headers.
 HTTP request headers are distinct from the
form data.
 Request headers are indirectly set by the
browser and are sent immediately following
the initial GET or POST request line.
Reading Request Headers from
Servlets
 The HTTPServletRequest object
provides the getHeader method,
which returns a String if the
specified header was supplied on
this request, null otherwise.
 Header names are not case-sensitive.
 There exist specific methods also to read
specific headers.
Reading Request Headers from
Servlets
 Getting the information on the main line:
 getMethod
 Returns the main request method :
 GET, POST,PUT, DELETE etc.
 getRequestURI
 Returns the part of the URL that comes after the host and
port but before the form data.
 For example, for the URL of
 http://randhost.com/servlet/search.BookSearch,
 getRequestURI would return
/servlet/search.BookSearch.
Reading Request Headers from
Servlets
getProtocol
Returns the third part of the request line, which specifies the
protocol used.

 Generally, the values are HTTP/1.0 or HTTP/ 1.1.

 Getting Header Names


 getHeaderNames method to get an Enumeration of all
header names received on this particular request.
Printing All Headers
Printing All Headers
Printing All Headers
Generating the Servlet Response
 The response from a servlet typically consists
of a
 status line,
 some response headers,
 a blank line, and the document.
 For example:
 HTTP/1.1 200 OK
 Content-Type: text/plain
 Hello World
Generating the Servlet Response
 The status line consists of the
 HTTP version, a status code (an integer) and a very
short message corresponding to the status code.

 All of the headers are optional except for the Content-


Type, which specifies the type of the document that
follows.

 The status line and response headers are manipulated in


many ways to carry out important tasks.
Generating the Servlet Response
 In the status line, the HTTP version is determined by the
server, and the message is directly associated with the
status code, the servlet needs to only set the status code.
 Use the setStatus method of the
HTTPServletResponse object to set the status.
 The setStatus method takes an int (the status code) as
an argument, but instead of using explicit numbers, it is
better to use the constants defined for them.
HTTP 1.1 Status Codes &
Purpose
 The following are the five categories in which all the status
codes lie:
 100-199 : Codes in the 100s are informational, indicating
that the client should respond with some other action.
 200-299 : Values in the 200s signify that the request was
successful.
 300-399 : Values in the 300s are used for files that have
moved and usually include a Location header indicating the
new address.
HTTP 1.1 Status Codes &
Purpose
 400-499 : Values in the 400s indicate an
error by the client.
 500-599 : Codes in the 500s signify an error
by the server.
 The constants in HttpServletResponse
that represent the various codes are derived
from the standard messages associated with
the codes.
HTTP 1.1 Status Codes &
Purpose
 200 (OK) : A value of 200 (SC_OK) means that everything
is fine. The document follows for GET and POST requests.
 This status is the default for servlets.
 201 (Created) : A status code of 201 (SC_Created) signifies
that the server created a new document in response to the
request; the Location header should give its URL.
HTTP 1.1 Status Codes &
Purpose
 205 (Reset Content) : A value of 205
(SC_RESET_CONTENT) means that there is
no new document, but the browser should
reset the document view.
 This status code is used to force browsers to
clear form fields.
 400 (Bad Request) : A 400
(SC_BAD_REQUEST) status indicates bad
syntax in the client request.
HTTP 1.1 Status Codes &
Purpose
 404 (Not Found) : (SC_NOT_FOUND)
Tells the client that no resource at that
address could be found.
 500 (Internal Server Error) : 500
(SC_INTERNAL_SERVER_ERROR) is the
generic “server is confused” status
code.
How the container handles a
request
HTTP Request
browser
GET
container
1 servlet

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.

 Step2 Creating new database: In the Services window, right-click the


MySQL Server node and choose Create Database. Create your own
database and this Database will appear under the MySQL Server node
in the Services window.
SQL Server Connectivity
 Step3 Creating Table: add a table either by using SQL editor or
using Create Table Dialog. In the database explorer under your
Database connection node, there are three sub folder: Table,
Views and Procedures. Using SQL editor, type the create table
query in SQL editor. And finally execute your SQL command.

CREATE TABLE Employee (id INT UNSIGNED NOT


NULL AUTO_INCREMENT, first_Name VARCHAR
(50), lastName VARCHAR (50), telephone VARCHAR
(25), email VARCHAR (50), PRIMARY KEY (id));
SQL Server Connectivity
 Or by using create table dialog, in the Database Explorer right
click the Table node and choose Create Table. This type of popup
will display. Specify all fields in the table.
SQL Server Connectivity
 Step4 working with table data: Choose Execute Command from the
Tables folder in the Database Explorer. A blank canvas opens in the
SQL Editor in the main window. Type the INSERT query:

INSERT INTO Employee Values(101,’JOHN’,…..)

Or when right click the client table and choose view data, the
created table displays:

You might also like