Você está na página 1de 78

Objectives

• Understand the Servlet Architecture.


• Compare Servlet & Other Similar
technologies.
• Understand the Servlet Life Cycle.
• Handle Request & Response.
• Generate Dynamic HTML.
• Handle Sessions.
Evolution of Dynamic Content Tech.

• Common Gateway Interface (CGI)


• ColdFusion (Allaire)
• Active Server Pages (ASP)
• Server-Side JavaScript (SSJS)
• Personal Home Page tools (PHP)
• Java Servlets
• JavaServer Pages
The CGI Life Cycle

Main Process
Request for CGI 1 Child Process for CGI 1

Request for CGI 2 Child Process for CGI 2

Request for CGI 3 Child Process for CGI 3

CGI-Based Web Server


Java Servlet A Java program that
extends the functionality of a Web server, generating dynamic
content and interacting with Web clients using a request
response paradigm.
J2EE 1.2 Architecture
An extensible Web technology that uses template data,
custom elements, scripting languages, and server-side
Java objects to return dynamic content to a client.
Typically the template data is HTML or XML elements.
The client is often a Web browser.
Advantages of Servlets
• Java™ objects which extend the
functionality of a HTTP server(a big plus).
• Dynamic customization of content
• Platform and server independent
• No CGI limitations
• better performance
• Easier to write than CGI code
 no need to parse headers and get info
(all that is done by the HttpServlet
class )
• No Networking restrictions (like applets)
• Do not create a new process (or Servlet for
every request)
• Servlets can persist over time
Server Extensions

Enhance or Change the base functionality


of the server, allowing the server to handle tasks
that were once relegated to external CGI
programs.
The Power of Servlets

• Portability
• Power
• Efficiency and Endurance
• Safety
• Elegance
• Integration
• Extensibility and Flexibility
The Servlet Life Cycle
• A web server
communicates with
a Servlet through a
simple interface,
javax.servlet.Servlet
. This interface
consists of three
main methods:
• init()
• service()
• destroy()
and two ancillary
methods:
• getServletConfig()
• getServletInfo()
Servlet Life Cycle (contd)

Main Process
Request for Servlet1 Thread JVM
Servlet1
Servlet1
Request for Servlet2 Thread

Thread Servlet2
Servlet2
Request
Servletforinitialized
Servlet1 once; reused until destroyed and
garbage collected.
Java Servlet-based Web Server
Servlet Life Cycle (contd)
Life Cycle Of A Servlet (contd)
• A servlet is constructed and initialized. It then services zero
or more requests until the service that it extends shuts down
• Initialized only once, stays resident in memory while
servicing requests
• Multiple threads of execute service(), one for each client
connection
• The servlet interface defines the life cycle methods :
 init()
 service()
 destroy()
init() Method

• Called by server immediately after servlet is


instantiated
• Called only once
• Servlet creates and initializes the resources
needed for handling requests

• public void init(ServletConfig config) throws


ServletException;

ServletException - thrown when servlet cannot


initialize necessary resources
service() Method

• It is the heart of the servlet.


• It handles all requests sent by a client.
• Each request message from a client results in a single
call to the servlet's service() method.
• It reads the request and produces the response message

• public void service(ServletRequest req,


ServletResponse res) throws ServletException,
IOException;
destroy() Method

• This signifies the end of a servlet’s life.


• It’s also a good place to save any persistent information
that will be used the next time the servlet is loaded.
• It is called to allow the servlet to clean up any
resources.
• Public void destroy();
Servlet Life Cycle (contd)
Servlet loaded on demand (first time
user accesses the servlet). Once loaded the
servlet is in memory
init()
Client requests
arrive
service()
Unloaded on closing server;
manual unloading
destroy()
each client request creates a
new thread with service
Servlet Interface

• Servlets Classes / Interfaces are available in packages


(in java servlet development kit)

– javax.servlet.http
– javax.servlet
Servlet Interface (contd)
GenericServlet Class
Server GenericServlet subclass

request service()
service()

response

KEY : implemented by subclass

A generic servlet handling a request


A Http Servlet Handling a Request

HTTP request HttpServlet subclass


Web Server
GET request doGet()
doGet()
response
POST request doPost()
doPost()
response service(
service(
HEAD request ))
response doHead()
doHead()
Implementation of doGet() doPost()… is to
return an error to the calling client if
servlet does
KEY : not override theseby methods.
implemented subclass
Generic servlet vs httpservlet

init service
Generic Servlet

destroy

extends
doGet(...) doOptions(…)

doPost(...) doDelete(…)
HttpServlet
doPut(…) doTrace(…)
What does the Server Receive
Searching
Found www.mcp.com
for www.mcp.com
server
client

GET /index.html HTTP/1.0


Server receives only one
of the HTTP request
methods (Get/Post)

http://www.mcp.com/index.html

Servlet programmers must provide


implementations for these requests
Web server recieves
GET /servlet/myHelloServlet
HttpServlet subclass
Check request type
Web Server it is “GET”
hence call doGet() doGet()
doGet()
GET/servlet/
myHelloServlet
service(
service( doPost()
doPost()
HTTP/1.0
))
Web server uses logic: doHead()
doHead()
myHelloServlet is loaded. If not , then load the servlet.
call service method (already implemented in HttpServlet)
(it checks the request type and correspondingly calls the
doGet() or doPost() method )
java.io javax.servlet Servlet
Servlet
InputStream
InputStream ServletInputStream
ServletInputStream
ServletConfig
ServletConfig
OutputStream
OutputStream ServletOutputStream
ServletOutputStream
ServletContext
ServletContext
Serializable
Serializable
ServletRequest
ServletRequest
java.lang
ServletResponse
ServletResponse
Object
Object GenericServlet
GenericServlet
SingleThreadModel
SingleThreadModel

Exception
Exception ServletException
ServletException UnavailableException
UnavailableException

KEY Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface extends implements
Servlet
Servlet
GenericServlet ServletConfi
ServletConfi
javax.servlet.* GenericServlet
gg
service(req, res) Serializabl
Serializabl
ee

ServletReques
ServletReques ServletRespons
ServletRespons
tt ee

ServletInputStream
ServletInputStream ServletOutputStream
ServletOutputStream

Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface implements
ServletContext / ServletConfig
• ServletConfig
– used to get initialization parameters
• getServletContext()
• String getInitParameter(String)
• Enumeration getInitParameterNames()
• ServletContext
– useful for logging & finding out about the
other servlets
• Servlet getServlet(String)
• Enumeration getServlets()
• Enumeration getServletNames()
• void log(String)
• void log(Exception, String)
GenericSer
GenericSer Serializabl
Serializabl
vlet
vlet ee

javax.servlet.http.* HTTPServlet
HTTPServlet

Class
Class ABSTRACT
ABSTRACTCLASS
CLASS Interface
Interface extends implements
Servlet Architecture

Methods for
Servlet managing a servlet and
communicating with
clients

HTTPServlet

Interface class extends


Encapsulates communication
from client to server

ServletRequest

GET request
Servlet
Servlet

response
ServletResponse

Encapsulates communication
from server to client
package codecamp; A Simple Code Example
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Public class ServletGet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse
response) throws ServletException,
IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First
Servlet</title>");
out.println("<big>Hello Code Camp!
</big>");
}
}
Example
Write the following html file: mydisplay.html
<HTML> <HEAD>
<TITLE> calling servlets </TITLE> </HEAD>
<BODY>
<form method=get
action="http://localhost:8080/servlet/servletGet">
<input type=submit value="call servletGet">
</form>
</BODY> </HTML>
Click on the button “call servletGet” and note that the
earlier servlet is called.

NOTE:User clicked on button, and the browser then


Eg: mydisplay.html
generated the GET method based on “action” settings.
Generating GET by clicking a
button on browser
Searching
Found localhost
for localhost
server
client

GET /servlet/servletGet
/mydisplay.html HTTP/1.0
HTTP/1.0

http://localhost…/…/mydisplay.html

call servletGet
Example
Modify only the following line in html file:
mydisplay.html
<form method=post
action="http://localhost:8080/servlet/servletGet">
Click on the button “call servletGet” and note what
happens.

NOTE:User clicked on button, and the browser then


generated the POST method based on “action” settings.

NOTE: the servlet servletGet did not contain a doPost


method and hence got the error. Rename doGet() to
doPost() and it would then work.
Transferring info from browser to Servlets
• Generally in web pages, users fill up a form
with fields.
• Browser communicates with server (servlets)
through GET and POST methods
• GET requests :
• – Getting information
• – Appended to the URL in a query string ( limited
• amount of data)
• – .../servlet/ViewCourse?name=servlets_codecamp
• – Can be bookmarked and emailed
• POST requests:
• – Sending information
• – Send any amount of data
• – .../servlet/PlaceOrderProcess
• – Can Not be bookmarked and emailed.
• – Use POST for things like placing an order.
Common Requests: GET and POST
• GET
• – Getting information
• – Appended to the URL in a query string ( limited
amount of data)
• .../servlet/ViewCourse?name=servlets_codecamp
• – Can be bookmarked and emailed
• POST requests:
• Sending information
• – Send any amount of data
• – .../servlet/PlaceOrderProcess
• – Can Not be bookmarked and emailed.
• – Use POST for things like placing an order.
Example

Write a html with three text fields for name, id and location,
with a submit button. Set the form method as ‘GET’, and
action as ‘servlet/servletGetParam’

Eg: servlet_get_HTML.html
Write a servlet with doGet() method. In the doGet() method
read the parameters and then send it back to the browser for
display

Eg: servletGetParam.java
Example

Write a html with three text fields for name, id and location,
with a submit button. Set the form method as ‘POST’, and
action as ‘servlet/servletGetParam’

Eg: servlet_post_HTML.html
Write a servlet with doPost() method. In the doPost() method
read the parameters and then send it back to the browser for
display

Eg: servletPost.java
Interface ServletRequest
– information about the client
• name of the host and the IP address of client
• parameters sent from the client browser
• scheme used by the browser to communicate
to servlet (eg. http; https; ftp;…..)
• protocol used by client (eg. ftp)
• access to the ServletInputStream (which
allows servlet to read binary data from the
client )
– information about server
• name of the server
• port used by the server
ServletRequest…

• Subclass ServletRequest to provide protocol specific


information

• Example: HTTPServletRequest (extends ServletRequest


)supports methods to retrieve more protocol specific
headers (getMethod() to identify the type of request)
javax.servlet.ServletRequest

class Name ServletRequest


String getContentType()
public
ServletInputStream getInputStream()
abstract String getParameter(String)
methods Enumeration getParameterNames()
String getProtocol()
BufferedReader getReader()
String getRemoteAddr()
String getServerName()
int getServerPort()
String getScheme()
String getRealPath()
String getCharacterEncoding()
Object getAttribute()
interface HTTPServlet
• Information from client
 additional path info (sent along with request)
• eg /servlet/myservlet/dict/defn.txt
• “/dict/defn.txt” is the additional info to the servlet
myservlet
• within your servlet use getPathInfo() (null if no such
data is available)
 what was requested (file/ servlet/)
 HTTP headers sent by the client
• Connection, User-Agent, host, Accept, Accept-
language, Accept-Charset
HTTP Headers

• General : Information not related to Client, Server or


HTTP protocol.
• Request : Preferred Document formats and server
parameters.
• Response : Information about the server.
• Entity : Information on the data that is being sent
between the client and server.
javax.servlet.http.HttpServletRequest

Class Name HTTPServletRequest extends ServletRequest


public
Enumeration getHeaderNames()
abstract long getDateHeader(String)
methods String getPathInfo()
String getQueryString()
String getRemoteUser()
String getAuthType()
Cookie[ ] getCookies()
String getRequestURI()
String getServletPath()
String getSession()
boolean isRequestedSessionIdFromCookie()
boolean isRequestedSessionIdFromUrl()
Example

Write a servlet that implements the doGet() method. Capture the


information encapsulated in the request object (in ServletRequest
and HTTPServletRequest), and send this info back to the client.

Eg: helloservletGet.java
ServletResponse Interface

• Allows the servlet to reply to the client


• Allows the servlet to set the content length and MIME
type
• Provides a handle to ServletOutputStream (or Writer)
to send data to the client
• Subclass HTTPServletResponse supports methods to
set more protocol specific headers
javax.servlet.ServletResponse

Class Name ServletResponse

public void setContentLength(int)


void setContentType(String);
abstract
ServletOutputStream getOutputStream()
methods
PrintWriter getWriter()
String getCharacterEncoding(String)
javax.servlet.http.
HttpServletResponse
Class Name HTTPServletResponse
public
void addCookie(http.Cookie)
abstract boolean containsHeader(String);
methods String encodeURL(String)
String encodeRedirectURL(String)
String encodeUri(String)
String encodeRedirectUri(String)
void setHeader(String,String)
void setIntHeader(String,int)
void setDateHeader(String,long)
void setStatus(int,String)
void sendError(int,String)
void sendRedirect(String)
Redirecting …
• Redirection can be set using the following methods in the
HttpServletResponse class
– setStatus(status code)
• status codes available in the HttpServletResponse class as
static variables
– setHeader(“Location”, “ give new site location here”)
• the new location must be an absolute url path
– setHeader(“Refresh”, “3”) will tell the browser for 3 seconds
before refreshing the page
– setHeader(“Refresh”, “3; URL=…..”) will tell the browser for 3
seconds before going to the new location specified in the
command.
Generating HTML

• Hardcoded in the program (servletGet.java)


• Using an HTML generator (require additional
software; html generation classes)
• Using an HTML generator creatively

Eg : ServletGet.java
Status Codes
Mnemonic constant Code Displayed Message

SC_OK 200 OK
SC_NO_CONTENT 204 No Content
SC_MOVED_PERMANENTLY 301 Moved Permanently
SC_MOVED_TEMPORARILY 302 Moved Temporarily
SC_NOT_FOUND 404 Not Found
SC_INTERNAL_SERVER_ERROR 500 Internal Server error
SC_NOT_IMPLEMENTED 501 Not Implemented
SC_SERVICE_NOT_AVAILABLE 503 Service Not Available
SC_BAD_GATEWAY 502 Invalid response
Redirecting a Request

• Servlet can use status codes and headers to inform a


client to use another URL. It is useful when
 document (html file) has moved.
 load balancing is required. (one machine can
distribute the load to many machines)
Abstract class HTTPServlet
class Name HTTPServlet extends GenericServlets implements
Serializable
protected void doGet(HttpServletRequest, HttpServletResponse)
methods long getLastModified(HttpServletRequest);
void doPost(HttpServletRequest, HttpServletResponse)
The service method supports HTTP
void doPut(HttpServletRequest, 1.0
HttpServletResponse)
void doDelete(HttpServletRequest, HttpServletResponse)
protocol.void
This method dispatchesHttpServletResponse)
doOptions(HttpServletRequest, each request
to the method designed to handle
void doTrace(HttpServletRequest, it.
HttpServletResponse)
void service(HttpServletRequest, HttpServletResponse)
public void service(ServletRequest, ServletResponse)

All methods throws ServletException and IOException


Overriding Methods

• Servlet writer who wants to handle the GET and the


HEAD (HTTP protocol) must override the doGet()
method in the servlet.
• Similarly override
– doPost() method to handle POST request
– doPut() method to handle PUT requests
– doDelete() method to handle DELETE requests
Notes

• Servlets are fundamentally multithreaded, hence can


run multiple service() methods.
• Therefore the code for service method must be thread
safe.
• If you do not want a multithreaded server then one
must implement the SingleThreadedModel interface.
Example

Write a counter servlet that counts the number of clients


served.

Eg: MyCounterServ.java

Modify the above servlet so that if many users are accessing


the variable count, it should be synchronized.

Eg: MyCounterServSyn.java
Example

Write a servlet that informs the client that the site has moved,
and allow let the browser go to the new url automatically
after 9 seconds.

Eg: RelocateServlet.java
Request Dispatcher

• The basic use of a RequestDispatcher:


One can effectively use the RequestDispatcher to call a JSP
from a servlet or a servlet from another servlet.
RequestDispatcher rd =

getServletContext().getRequestDispatcher("
/welcome.jsp");

rd.include(request, response);
Sending Multimedia Content

• To send an image that is available with the server to the


client
 open a stream to the client browser
 open the local image file
 read block of bytes/ or byte by byte of image
 send information to server by writing to the stream
Example

Write a serlvet that sends an image to the browser.


Image file must be on the server system.

Eg: servletImage.java
Problem: If we write 2 images to the
application, it will read only the first one.
Hence, one can send only one image at a
time.
Example

Write a serlvet that sends 2 <img src=“……”> tags to the


client. The client would load one image after another and
display both of them.

Eg: servletImageHTML.java
Note: All the
Solution: senddata
the to
html
be sent
tag <img
is stored
src=“…”>,
in a and the
browser will open connection
byteArrayOutputStream and and
sent get
all at
theonce.
information
This is
from server.
buffering butThis
could
wayslow
any
down
number
whenoflotimages
of information
can be is
passed.
being sent to the client.
User Authentication

• Specify in the resource list


• servlet resource/ and what type of authentication
• once set, then the browser gives a dialog box and
then sends the name and password to the servlet

Eg: secureServlet.java
Session Tracking

• Mechanism to maintain a state about a series of


requests from the same user (request originating from
same browser)
• Sessions are shared across servlets
• HttpSession Object
 Can Store (name, value) Pairs.
 Persistence and disk swapping through Object
Serialization.
 Works across protocols (HTTP/HTTPS).
 Session validity, Creation time etc.
Session Tracking (contd)

procedures in session tracking


• get a HttpSession object for a user
 HttpSession ss = new HttpSession(true)
true means that if it a new session create a new
session object, otherwise get session id.
• store/get data from the HttpSession object
 void ss.putValue(String name, Object val)
 Object ss.getValue(String name)
 void ss.removeValue(String name)
• Invalidate the session
 ss.invalidate();
Count Example using Session

Write a servlet that uses session api to track the number of


times a user has visited the site.

Eg: SessionDemo.java
Ways of Session-Tracking

• Hidden Form Fields


• Persistent Cookies
• Servlet API
Security Issues

• The Servlet Sandbox


• Access Control Lists (ACLs)
Servlet Sandbox

• It is an area where Servlets are given restricted


authority on the server.
• They may not have access to the file system or
network, or they may have been granted a more
trusted status.
• It is up to the web server administrator to decide
which servlets are granted this status.
Access Control Lists

• An ACL is a list of users who are allowed to perform a


specific function in the server.
The list specifies:
 What kind of access is allowed
 What object the access applies to
 Which users are granted access
Servlet Environment

• Inter-Servlet Communication
How to call a method of another Servlet
Servlet Environment (contd)

• Communication with Active Server Resources


 How to call another Servlet (or any other kind of
active resource) to process a request
• Accessing Passive Server Resources
 How to access a resource in the server's document
tree
• Accessing Servlet Resources
 How to access resources which belong to a Servlet
• Sharing Data Between Servlets
 How to share data between Servlets
Invoking a Servlet From an Applet

HTTP Request thru DataOutput created by


URLCorrection object

Formatted results thru DataInputStream object


created by URLConnection object
SQL Query
ResultSet Object
Exercise (contd..)

• 20. Due to the implementation of the application on the


AWT framework it is required to install the JRE software
& the required application components on each machine
which needs to communicate with the application. A better
alternative would be to implement the same in a http based
server architecture,(repeat exercises 1 to 5 here)[20]
ThankQ

Você também pode gostar