Servlets Ix - SLATE

makeshiftklipInternet and Web Development

Oct 31, 2013 (3 years and 10 months ago)

52 views

Servlet

Web Application

Web Application


An application that is accessed over a network whether an
internet or intranet known as web application..


In 3
-
tier application, a web application (presentation) defines
the first tier contains different dynamic web content
technologies (i.e., Servlet, JSP, ASP.NET, PHP, …)


Basic web application flow:

1.
Client software send request to
Web Server

2.
Web server loads the corresponding
components

from its
container

3.

Application process the
client request

and
generate response

4.
Web server sends the response to the client


A web application has its configuration files and resources to
use which are
defined by the Servlet/JSP specifications and are
managed by the container

J2EE Containers

& Components


Container

is a server which maintains control and
provides services through an interface or framework


Component

use the protocols and methods of the
container to access other application components
and services provided by the server.


Purpose of container:


Provides
the runtime environment for the
components


Manages the components, such as, creation, request,
destruction, …


Handles the contract for services regarding components,
such as, transaction, security, …


Specifies
the deployment model for components
.


Types
of J2EE Containers


Four types:

1.
Application client container:
It is for stand
-
alone
application, i.e., Desktop (GUI) or Console

2.
Applet container:
It is for applet based application.


Runs in the Browser


Uses the Java
-
Plug
-
In

3.
Web container:

It is for Web applications, i.e.,
Servlet, JSP, …

4.
EJB container:
It is for EJB components.

Web Container


Used to host web applications


Servlet container or Servlet engine


Extends the web server functionality


Provides the environment to run Servlets and JSPs


Automatically instantiates and initializes the Servlets on
application startup or at first invocation


Container calls the service() method (get, post, destroy,
…) when user requests the servlet


Responsible for managing life cycle of
Servlets and JSPs


Provides the network services
to sent request
and
response

Web Server


A server which is capable of:

1.
Receiving HTTP requests

2.
Interpreting requests, processing them,
create corresponding responses

3.
Sending HTTP
Responses to the
appropriate clients (i.e., Browser)


It communicates through HTTP
(
Hyper Text
Transfer Protocol
),
known as HTTP Server


Examples:
Apache Tomcat
,
GlassFish
,
JBoss
, …

Application Server


A complete server, which:


Provides an environment for running the web
applications (Web Server)


Provides an environment for running the business
components, such as, EJBs, …


Examples:
GlassFish
,
JBoss
, Bea
WebLogic
, IBM
WebSphere
, Oracle Application Server, …

HTTP (Hypertext Transfer
Protocol)


Used
for the vast majority of transactions on World Wide Web


Every web page you visit is transmitted using
HTTP prefix


http://


Basically
stateless, i.e.,
does
not require the server to retain
information or status about each user for the duration of
multiple
requests


Relies on client, usually a web browser, to make a request and
a server to send a response


HTTP client opens a socket connection to an HTTP server


Issues an HTTP request


Receives an HTTP response (stream of data)


Connections for the protocol last long enough for one
transaction, i.e., one
or more request/response pairs


HTTP
Request
-
Response Flow

1.
HTTP Server listens for requests (default is port
80)

2.
HTTP Client creates an
URL


URL designates protocol, hostname, optional port number,
path, query

3.
HTTP Client Software creates a TCP / IP socket
connection

4.
HTTP Server accepts socket Request

5.
HTTP Client Software creates HTTP Request

6.
HTTP Client Software sends HTTP Request
through the open TCP/IP socket
connection

7.
HTTP Server receives / parses HTTP
Request

HTTP Request
-
Response Flow

8.
HTTP Server handles Request, taking whatever
action is required

9.
HTTP Server generates HTTP Response

10.
HTTP Server passes HTTP Response back over
TCP/IP socket connection

11.
HTTP Client Software receives / parses HTTP
Response

12.
HTTP Client Software takes any action required

13.
HTTP Client Software closes socket connection

14.
HTTP Client Software passes Response data to
HTTP Client

HTTP Basics


HTTP Request contains:


Request
Method


Resource ID


HTTP Version


Header Name and Value Pairs (data about HTTP Client SW or
Request or Response)


Blank
line


Request
Body


HTTP Response contains:


HTTP Version


HTTP Status
Code


HTTP Status Description


Header Name/Value Pairs


Blank Line


Response Body

HTTP Request
Instance Example

GET / default.htm HTTP/1.1

Accepts: text/plain, text/html
, image/jpeg,
image/gif

User
-
Agent:
Mozilla/4.0
(compatible; MSIE 5.5; Windows NT
5.0)

(data here if any
-

after 1 blank line)


HTTP
Response Instance
Example

HTTP/1.1 200 ok

Date: Sat, 26 Jan
2010
21:35:20
gmt

Server: Apache/1.2.5 FrontPage/3.0.4

Connection: close

Content
-
Type: text/html


<!DOCTYPE HTML PUBLIC “
-
//W3C//DTD HTML

3.2//EN”>>


<HTML>


<!
--

html to end…
--
>

</HTML

HTTP Methods


GET
-

Requests document with data appended to
URL


HEAD

-

Requests document header; body is stripped
by web server


POST
-

Requests data be acted upon by server with
data passed as name
-
value pairs in the body (as in
web forms)


PUT
-

Request the server store or replace a
document


DELETE
-

Requests the server delete a document


OPTIONS
-

Request the HTTP server provide the
client with configuration options


TRACE
-

used for debugging


HTTP
Methods (GET & POST)


GET
:


Contacts server and sends data in single step


Appends data to
request
URL separated by question
mark,
i.e.,
provides limited amount of information using query
strings


Web servers restrict length of URLs + query string to 255
characters, so extra information ignored or lost


Designed to get
information, i.e., visible on browser


POST
:


Data sent in two steps

1.
Browser contacts server

2.
Sends data


Reliable way to submit data on web server:


using name
-
value pairs with no limitations on variables


hidden values remain hidden

Servlet


Servlets are
server side Java
programs that serve
as an intermediating layer between an HTTP
request of a client and applications in the Web
server


Extend the functionality of a HTTP server


Dynamic contents generation


Receives HTTP requests and Returns
HTTP
responses


Runs
within a JVM


Utilize the services of a
web container


Deployed on web server

Basic
Servlet Working

Servlets Receive Request Flow

Receive Request for

Servlet
S

Is
S
loaded?

Is
S
current?

(re)Load
S

Forward Request

to
S

Servlets die when
Servlet Server dies

Loaded when first used,

or after modified

no

no

yes

yes

Servlet API


javax.servlet.*

contains all servlet classes


The
Servlet

interface defines methods that manage
servlets and their communication with clients


ServletRequest


ServletResponse


YourOwnServlet

(concrete class)

HttpServlet

(concrete class)

Generic
Servlet

(abstract class)

Servlet

(interface)

Servlet Life Cycle


No
main()

method
!


Basic Flow:

1.
Server/Container
creates
a servlet instance

(
1

instance)

2.
Server/Container
calls
servlet’s
init
()
method


one time
only

3.
Servlet
instance
service()
for each request in a new
thread (
1

thread for
1

client)


Servlet

calls appropriate
doXXX
()
method

4.
Server/Container
calls
servlet’s
destroy()
method
to
remove (Server may hold servlet for more later
requests)

Servlet Life Cycle Flow

Servlet Class

Initialization

and Loading

Calling the

init

method

Servicing requests by

calling the

service

method

Destroying the servlet


by calling the

destroy

method

Garbage

Collection

ServletConfig

The
init
( )
method

public void
init
() throws
ServetException

{


// initialization code here

}


init
()
is called only one time, when servlet is
instantiated


The service( ) method


Acts as a dispatcher for the HTTP Request


Determines the type of request (GET, POST, HEAD,
OPTIONS, DELETE, PUT, TRACE)


Calls the appropriate
doXXX

method (normally
doGet
()
or
doPost
()
)


Do
NOT
override
service()
: If you want to use the same
code in
doGet
()
and
doPost
()
, call
doGet
()
from
doPost
()
(or
vice versa)


public void service(
HttpServletRequest

req
,
HttpServletResponse

resp
) throws
ServletException
,
IOException

{

// code here

}

The
doXXX

Methods (
doGet
,
doPost
…)

public void
doGet
(
HttpServletRequest

req
,
HttpServletResponse

resp
) throws
ServletException
,
IOException

{

// code here

}



Same signature for
doPost
()
, etc.


Override these methods as needed


except override not needed for OPTIONS and
TRACE (normally supported by
service()
method)


HttpServlet

Request Handling

GET request

service()

HttpServlet

subclass

response

doGet
()

doPost
()

Web
Server

POST request

response

The destroy( ) method


Called once when servlet is destroyed


Allows to:


halt background threads


store settings or other data


close database connections


other similar cleanup


Will NOT be called if Web server crashes or
other system failure occurs


Keep your application in a consistent state by
periodically updating persistent
data

Basic Servlet Example

import java.io.*;

import
javax.servlet
.*;

import
javax.servlet.http
.*;


public class
HelloServlet

extends
HttpServlet

{



public
void
doGet
(
HttpServletRequest

req
,
HttpServletResponse

resp
)


throws
ServletException
,
IOException

{





PrintWriter

out =
resp.getWriter
();




out.println
( “<HTML>
\
n”);



out.println
(“<HEAD><TITLE>Hello CS</TITLE><HEAD>
\
n”);



out.println
(“<BODY>
\
n”);



out.println
(“<H1>Hello
SE 343</
H1>
\
n”);



out.println
(“</BODY></HTML>”);



out.close
();



}

}
// end class
HelloCSServlet

Discuss: Servlet Example Code


To be a
servlet:


A class
should extend
HttpServlet


Override
doGet

or
doPost

method (as per requirement)


doGet

and
doPost

take
two arguments
:


HttpServletRequest


methods for finding out about incoming
information,
such
as,
FORM data
and HTTP request
headers


HttpServletResponse


methods
that let you
specify
responses on requests and response
headers (Content
-
Type,
…)


Obtains
a
PrintWriter

used to send output back to the client


For simple servlets, most of the effort is spent
on
println

statements that generate the desired HTML
page

Configuration file


The configuration file include the web.xml file


This configuration file customizes the resources of a web
application in an efficient and structured fashion


The web.xml file is kept in a WEB
-
INF folder within the
web application’s directory


a private folder


Configuration File (web.xml)


<?xml version="1.0" encoding="ISO
-
8859
-
1"?>


<!
DOCTYPE

web
-
app PUBLIC "
-
//Sun Microsystems,
Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/
dtd
/web
-
app_2_3.dtd">


<
web
-
app>


<
display
-
name> The name of the application </display
-
name>


<
description> C'mon, you know what goes into a description, don't you?
</description
>



<
context
-
param
>


<
param
-
name>
name_of_context_initialization_parameter
</
param
-
name
>


<
param
-
value>
value_of_context_initializtion_parameter
</
param
-
value
>


<description
> Again, some description </description>


</
context
-
param
>

Configuration File (web.xml)


<
servlet
>


<servlet
-
name>
guess_what_name_of_servlet
</servlet
-
name>


<description>Again, some description</description>


<servlet
-
class>
com.foo
-
bar.somepackage.TheServlet
</servlet
-
class>


<
init
-
param
>


<
param
-
name>foo</
param
-
name>


<
param
-
value>bar</
param
-
value>


</
init
-
param
>


</servlet>


<
servlet
-
mapping
>


<servlet
-
name>
name_of_a_servlet
</servlet
-
name>


<
url
-
pattern>*.
some_pattern
</
url
-
pattern>


</servlet
-
mapping
>

Configuration File (web.xml)


<
servlet
-
mapping
>


<servlet
-
name>image</servlet
-
name>


<
url
-
pattern>/image</
url
-
pattern>


</servlet
-
mapping>


<
session
-
config
>


<session
-
timeout>30</session
-
timeout>


</session
-
config
>


</web
-
app>


To get value from Configuration File


String value =
getServletContext
().
getInitParameter
("
name_of_context
_initialization_parameter
");



Example:
String
value =
getServletConfig
().
getInitParameter
("foo");

Questions?