Servelet API
Servelet API
HTTP
⚫ HyperText Transfer Protocol
⚫ Stateless request/response client-server protocol
⚫ Requests:
⚫ Method: GET, POST, HEAD, TRACE, OPTIONS, PUT,
DELETE
HTTP
⚫ Requests, continued
⚫ URI (required in HTTP/1.1)
⚫ Header Fields
⚫ E.g. how the response should be returned, under what conditions,
identification and characterization of client, accounting data
⚫ Body
⚫ POST data
⚫ Empty for GET
HTTP
⚫ Response:
⚫ Status code (machine), reason (human)
⚫ Header
⚫ Metadata, e.g. Content-Type (Media type), Content-Length,
Last-Modified, Etag
⚫ Body
⚫ (X)HTML, other XML, text, binary data …
URL Connections
⚫ java.net also -- connections extend Socket
⚫ Encapsulates HTTP and FTP connections
⚫ URI, URL, URLConnection,
HttpURLConnection
Servlets Definition
⚫ Server side component in a client server model (now the
browser is the client )
⚫ Reside in a servlet container, assigned to a certain URL
pattern.
⚫ Provide mechanisms for maintaining state over the
stateless HTTP protocol
Servlet Model
Servlet API
⚫ Interfaces:
⚫ HttpServletRequest
⚫ HttpServletResponse
⚫ HttpSession
⚫ HttpBindingSession
⚫ HttpSessionContext
⚫ Interfaces are implemented by server providers and can be
used out of the box
Servlet API
⚫ Classes
⚫ Cookie
⚫ HttpServlet
⚫ HttpSessionBindingEvent
⚫ HttpUtils
Servlet Lifecycle
Servlet Lifecycle
⚫ Multithreaded access (usually default)
⚫ init called first time only (by the container)
⚫ zero to many calls to service
⚫ destroy called
init (ServletConfig)
⚫ call super.init (config), or just use init ()
⚫ Called once
⚫ Prior to any call to service
⚫ Don’t worry about multithreading issues here
⚫ Sometimes used to get resources needed for the lifetime of
the servlet
service (req, resp)
⚫ Not usually overridden
⚫ Default impl. determines what request handler to call (based
on HTTP request type), calls it
⚫ Service method will call doGet, doPost, doPut, etc.
based on service type.
⚫ Default implementations provided for doHead,
doTrace, doOptions
doPost, doGet, etc.
⚫ doPost (HttpServletRequest req,
HttpServletResponse resp)
⚫ Implement this to handle POSTs
⚫ Read from req, build resp
⚫ Multithreaded access by default (depending on server config)
⚫ Beware instance variables, shared data
⚫ config and context are shared, session is usually safe,
req/resp are not
⚫ Use locks and/or synchronized data structures if shared data is an issue
destroy ()
⚫ called once
⚫ Servlet timeout, servlet reload, container shutdown
⚫ Other threads may still be processing service requests, no
further requests will be processed
⚫ Release resources, write data, etc.
Servlet Skeleton
import javax.servlet.*
import javax.servlet.http.*
import java.io.*