Java Servlets

milklivereddeepInternet and Web Development

Nov 13, 2013 (3 years and 5 months ago)

54 views

1
Java Servlets
Jay Urbain, Ph.D.
Credits:
Official Tutorial:
http://docs.oracle.com/javaee/6/tutorial/doc/bnafd.html
Basham, Sierra, Bates, Bert. Head First Servlets and JSP. O'Reilly.
Scott Adams
2
Interaction between web clients and servers is
structured around HTTP Request and Response
messages
3
Server is running a web server,
like Apache or Microsoft IIS.
In a basic scenario, the Server responds to a browser
GET request by returning a staticHTML file
4
Note: This diagram can
be found in your textbook
A web server can employ a
Helper App
when it needs to go beyond serving
static web pages
5
parameters
CGI
*
programs can be written
in Perl, Python, PHP, C, or
Java
*Common Gateway Interface
HTTP GET or POST request
(may include parameters)
CGI
Helperapp
6
Parameters: HTML <form> tag element
<form action
="http://<url>"
method=“post"
>
<!--form elements go here -->
</form>
The opening <form>
tag –all form
elements go between
the opening and
closing tag.
The required
action
attribute specifies
the URLofwhere to send the form’s
data.
…and the name of
the Web Resource
that will process the
form data if it is
submitted
The
method
attribute
specifies which HTTP
method will be used to send
the data in the form to the
server –default is “get”
Note: See the examples
on the course website
GET vs. POST scenarios
7
Note: This diagram can
be found in your textbook
8
get
specifies that a HTTP GET method should be used,
which appends the form data to the end of the URL –
new examplsand graphics
http://<domain>/<resource>?firstname=Arnold&last
name=Ziffel
￿
“get something back from the
server”
￿
getrequests have a limit of 256
characters
￿
The data is plainly visible in the
URL (insecure!)
￿
You can bookmark a page that
is the result of submitting a
form
￿
Use GET to submit small
amounts of insensitive data
which the server app will NOT
use to modify its internal state
￿
Also helpful for debugging
9
post
specifies that a HTTP POST method should be used, which
appends the form data to the end of the HTTP POST header
•There is no limit on the size of the data packet that
can be sent to the server
•You cannot bookmark a URL that was generated as a
POST message, since the form data is not in the URL
•A post request can be encrypted in order to protect
sensitive data, such as a credit card numbers or
passwords
•Use POST to send form data that
–Is sensitive (use encryption in that case)
–Will change the state of the web application
Note: Detailed explanation on pp 112-114 in your text.
Anatomy of GET HTTP request
10
Anatomy of POST HTTP request
11
HTTP Methods
•Note: no doConnect()
12
13
How it works in general
14
Note: This diagram can
be found in your textbook
User enters a URL (or
clicks a link) to a CGI
program rather than a static
page
Web server “sees” that the
request is for a helper
program, so the server runs
the helper, sending along any
parameters
sent from the
Client.
The helper app constructs the brand new
(dynamic) page and sends the HTML
back to the server.
Too simplistic
What does a Container like Tomcat do?
Provides run-time environment for Servlets via Servlet inteface
•Communication
–Creates server-side sockets
–Listens for client connections
–Determines client HTTP request type and “decodes” HTTP headers
•ServletLifecycle management
–Figures out which Servletshould be used to process a specific request
–Handles Servletclass loading
–Handles Servletinstantiation/construction
–Handles Servletinitialization
•Servletexecution support
–Launches/manages threads that service each incoming request
–Handles Servletservice() method invocation
–Creates and passes Request and Response objects to the Servlet
•Supports Security
•Supports JSP
16
How Tomcat manages Servlets
17
Note: This diagram can
be found in your textbook
Servlet Lifecyle
18
Tomcat invokes a Servlet’s service() method, but your
HTTPServlet-derived class should override doGet() or doPost()
19
The service() method is given an
implementation in the HTTPServlet
base class, where the doGet() and
doPost() methods are called.
You must override these methods in
your HttpServlet-derived class
20
class Servlet-api classes
java.io.Serializable
HttpServlet
# doDelete(HttpServletRequest, HttpServletResponse) : void
# doGet(HttpServletRequest, HttpServletResponse) : void
# doHead(HttpServletRequest, HttpServletResponse) : void
# doOptions(HttpServletRequest, HttpServletResponse) : void
# doPost(HttpServletRequest, HttpServletResponse) : void
# doPut(HttpServletRequest, HttpServletResponse) : void
# doTrace(HttpServletRequest, HttpServletResponse) : void
# getLastModified(HttpServletRequest) : long
+ HttpServlet() : void
# service(HttpServletRequest, HttpServletResponse) : void
+ service(ServletRequest, ServletResponse) : void
java.lang.Object
java.io.Serializable
GenericServlet
+ destroy() : void
+ GenericServlet() : void
+ getInitParameter(String) : String
+ getInitParameterNames() : Enumeration
+ getServletConfig() : ServletConfig
+ getServletContext() : ServletContext
+ getServletInfo() : String
+ getServletName() : String
+ init(ServletConfig) : void
+ init() : void
+ log(String) : void
+ log(String, Throwable) : void
+
service(ServletRequest, ServletResponse) : void
java.lang.Object
«interface»
Servlet
+ destroy() : void
+ getServletConfig() : ServletConfig
+ getServletInfo() : String
+ init(ServletConfig) : void
+ service(ServletRequest, ServletResponse) : void
java.lang.Object
«interface»
ServletConfig
+ getInitParameter(String) : String
+ getInitParameterNames() : Enumeration
+ getServletContext() : ServletContext
+ getServletName() : String
-config
A Servlet is just a Java class that implements specific interfaces (defined by the
Java Servlet Specifications) that are used by the Container
21
All Servletsmust
implement these 5
methods
Abstract class.
Implements most of
the basic servlet
methods
Implements the service() method
and calls doGet(), doPost() etc as
appropriate
NOTE
•The Java classes pertaining to Servletsare notpart of the
standard 1.6 SE
–They are part of the
Java EE
specification
•Implementation of the 1.6 SE is provided in the 1.6
JDK/JRE System Library
–This is the library you are probably most familiar with
–rt.jaris the main jarfilein this library
•Container vendors supply the implementation of the
classes that are part of the Servletspecification
–Tomcat comes with its own Servletlibraries
–servlet-api.jarimplements the Servlet-related classes
22
23
These contain info relevant to your
Web app
Servletexecution –Part 1 of 2
24
Servletexecution –Part 2 of 2
class Request classes
java.lang.Object
servlet::ServletRequestWrapper
+ getAttribute(String) : Object
+ getAttributeNames() : Enumeration
+ getCharacterEncoding() : String
+ getContentLength() : int
+ getContentType() : String
+ getInputStream() : ServletInputStream
+ getLocalAddr() : String
+ getLocale() : Locale
+ getLocales() : Enumeration
+ getLocalName() : String
+ getLocalPort() : int
+ getParameter(String) : String
+ getParameterMap() : Map
+ getParameterNames() : Enumeration
+ getParameterValues(String) : String[]
+ getProtocol() : String
+ getReader() : BufferedReader
+ getRealPath(String) : String
+ getRemoteAddr() : String
+ getRemoteHost() : String
+ getRemotePort() : int
+ getRequestDispatcher(String) : RequestDispatcher
+ getScheme() : String
+ getServerName() : String
+ getServerPort() : int
+ isSecure() : boolean
+ removeAttribute(String) : void
+ ServletRequestWrapper(ServletRequest) : void
+ setAttribute(String, Object) : void
+ setCharacterEncoding(String) : void
«property get»
+ getRequest() : ServletRequest
«property set»
+ setRequest(ServletRequest) : void
java.io.InputStream
servlet::ServletInputStream
+ readLine(byte[], int, int) : int
# ServletInputStream() : void
java.lang.Object
«interface»
servlet::ServletRequest
java.lang.Object
«interface»
http::HttpServletRequest
http::HttpServletRequestWrapper
+ getAuthType() : String
+ getContextPath() : String
+ getCookies() : Cookie[]
+ getDateHeader(String) : long
+ getHeader(String) : String
+ getHeaderNames() : Enumeration
+ getHeaders(String) : Enumeration
+ getIntHeader(String) : int
+ getMethod() : String
+ getPathInfo() : String
+ getPathTranslated() : String
+ getQueryString() : String
+ getRemoteUser() : String
+ getRequestedSessionId() : String
+ getRequestURI() : String
+ getRequestURL() : StringBuffer
+ getServletPath() : String
+ getSession(boolean) : HttpSession
+ getSession() : HttpSession
+ getUserPrincipal() : Principal
+ HttpServletRequestWrapper(HttpServletRequest) : void
+ isRequestedSessionIdFromCookie() : boolean
+ isRequestedSessionIdFromURL() : boolean
+ isRequestedSessionIdFromUrl() : boolean
+ isRequestedSessionIdValid() : boolean
+ isUserInRole(String) : boolean
-request
provides access to
The HTTP Request Wrapper Class
25
A reference to an HTTPServletRequestis
created by the Container
and passed to the doGet() and doPost()
methods of an HTTPServlet
These methods are about
HTTP things like headers,
sessions, and cookies
The HTTP Response Wrapper Class –
setAttribute?
26
A reference to an HTTPServletResponseis created by the Container
and passed to the doGet() and doPost() methods of an HTTPServlet
class Response Classes
java.io.OutputStream
servlet::ServletOutputStream
java.lang.Object
servlet::ServletResponseWrapper
+ flushBuffer() : void
+ getBufferSize() : int
+ getCharacterEncoding() : String
+ getContentType() : String
+ getLocale() : Locale
+ getOutputStream() : ServletOutputStream
+ getWriter() : PrintWriter
+ isCommitted() : boolean
+ reset() : void
+ resetBuffer() : void
+ ServletResponseWrapper(ServletResponse) : void
+ setBufferSize(int) : void
+ setCharacterEncoding(String) : void
+ setContentLength(int) : void
+ setContentType(String) : void
+ setLocale(Locale) : void
«property get»
+ getResponse() : ServletResponse
«property set»
+ setResponse(ServletResponse) : void
http::HttpServletResponseWrapper
+ addCookie(Cookie) : void
+ addDateHeader(String, long) : void
+ addHeader(String, String) : void
+ addIntHeader(String, int) : void
+ containsHeader(String) : boolean
+ encodeRedirectURL(String) : String
+ encodeRedirectUrl(String) : String
+ encodeURL(String) : String
+ encodeUrl(String) : String
+ HttpServletResponseWrapper(HttpServletResponse) : void
+ sendError(int, String) : void
+ sendError(int) : void
+ sendRedirect(String) : void
+ setDateHeader(String, long) : void
+ setHeader(String, String) : void
+ setIntHeader(String, int) : void
+ setStatus(int) : void
+ setStatus(int, String) : void
java.lang.Object
«interface»
http::HttpServletResponse
java.lang.Object
«interface»
servlet::ServletResponse
-response
provides access to
These methods are also
about HTTP things like
headers, sessions, and
cookies
27