Parsing HTTP Requests Handling Connections To Web Clients
Parsing HTTP Requests Handling Connections To Web Clients
Parsing HTTP Requests Handling Connections To Web Clients
get/post
Client 2
-HTML Servlet1 Servlet2
form
2
Life Cycle
● A servlet is accessed through a URL, just as if it were a file or a
CGI program.
● When a request for a particular servlet is received, the Java Server
invokes the servlet as a separate thread of execution.
● Once started, it can receive environment information as well as
client query information similar to that provided through the CGI. It
processes the request and returns its data, formatted as HTML, to be
included in the body of the HTTP response generated by the Java
Server.
● The servlet is then destroyed by the Java Server.
3
Servlet uses
● can process data which was POSTed over HTTPS using an HTML
FORM, passing data such as a purchase order (with credit card
data).
● servlets handle multiple requests concurrently: requests can be
synchronized with each other to support collaborative applications
such as on-line conferencing.
● servlet can forward requests other servers.
– balance load among several servers which mirror same content.
● …..
– cgi servlet can handle cgi requests
– file loader servlet can handle file loading requests
– ...
4
Class Hierarchy
● Servlets are implemented using the Java Servlet API.
● All servlets implement the Servlet interface.
– extend either the GenericServlet class, which implements the
Servlet interface, or its subclass, HttpServlet.
● 2 packages: javax.servlet and javax.servlet.http.
● not part of the core Java framework, so do not begin with java. part of the
Standard Java Extension API, begin with the keyword javax.
● Create a servlet as an extension of HttpServlet (which is a subclass
of GenericServlet, which implements Servlet interface).
5
Servlet model
The simplest possible servlet defines a single method, service:
import javax.servlet.*;
● Input and output streams may be used with data in whatever format
is appropriate.
– object serialization
– HTML
– image formats 7
Environment, State
● Servlets are java objects, so they:
8
Class Hierarchy
● Servlets are implemented using the Java Servlet API.
● All servlets implement the Servlet interface.
– extend either the GenericServlet class, which implements the
Servlet interface, or its subclass, HttpServlet.
● 2 packages: javax.servlet and javax.servlet.http.
● not part of the core Java framework, so do not begin with java. part of the
Standard Java Extension API, begin with the keyword javax.
● Create a servlet as an extension of HttpServlet (which is a subclass
of GenericServlet, which implements Servlet interface).
9
Servlet methods
● After being loaded, servlet life cycle includes three methods:
● init() - server activates servlet
– perform potentially costly (usually, I/O intensive) setup only
once, rather than once per request.
● initializing sessions with other network services or
● getting access to their persistent data (stored in a database or file).
● service() - servlet handles many requests. Each client request
generates one service() call.
– requests may be concurrent; allows servlets to coordinate
activities among many clients.
– Class-static state may be used to share data between requests.
● destroy() - requests processed until servlet is explicitly shut down
by the web server, by calling the destroy method.
– Servlet's class may become eligible for garbage collection.
10
Security
● Servlets have access to information about their clients. Servlets
relying on HTTP have access to HTTP-specific authentication data.
● Unlike any other current server extension API, Java Servlets
provide strong security policy support. Java environments provide a
Security Manager which can be used to control whether actions
such as network or file access are to be permitted.
● By default, servlets loaded over the network are untrusted, not allowed to
perform operations such as accessing network services or local files.
● Only servlets built in to the Java Web Server, and those in a specific local
.../servlets directory controlled by server administrator are fully trusted
and granted all privileges.
● However, servlets which have been digitally signed as they were put
into Java Archive (JAR) files, can be trusted and granted more
permissions by the security manager.
● A digital signature on executable code indicates that the organization
which signed the code "vouches for it" in some sense. 11
12
Creating Servlets
● 0. Log onto sol.scudc.scu.edu
● 1. setup jdk-1.2
● 2. Set classpath to include JavaWebServer packages, jdk
– CLASSPATH=.:/opt/jdk-
1.2/sol2.7:/users/lseiter/JavaWebServer2.0/lib/servlet.jar
– (also add oracle jar if you want to use jdbc oracle driver)
– /users/lseiter/classes/classes111.zip
● 3. Write and compile servlet (example: MyServlet.Java)
● 4. Copy servlet (MyServlet.class) to appropriate directory
– servlet directory in JWS (trusted)
– classpath of JWS
– arbitrary directory (untrusted, must be signed, etc.)
● 5. Invoke servlet
13
● http://sol.scudc.scu.edu:8080/servlet/students.swtoolsxx.MyServlet
public class SimpleServlet extends HttpServlet {
/*** Handle the HTTP GET method by building a simple web page.*/
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out;
// set content type and other response header fields first
response.setContentType("text/html");
// then write the data of the response
out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println(title);
out.println("</TITLE></HEAD><BODY>");
out.println("<H1> Simple Servlet Output </H1>");
out.println("<P>This is output from SimpleServlet.");
out.println("</BODY></HTML>");
out.close();
}
}
14
When a servlet accepts a call from a client, it receives two objects: A
ServletRequest, encapsulates communication from client to the
server. A ServletResponse encapsulates communication from server
to client An HttpServletRequest object provides access to HTTP
header data, such as any cookies found in the request and the HTTP
method with which the request was made. The HttpServletRequest
object also allows you to obtain the arguments that the client sent as
part of the request. To access client data:
● The getParameter method returns the value of a named parameter. If your
parameter could have more than one value, use getParameterValues
instead. The getParameterValues method returns an array of values for the
named parameter. (The method getParameterNames provides the names
of the parameters.)
● For HTTP GET requests, the getQueryString method returns a String of
raw data from the client. You must parse this data yourself to obtain the
parameters and values.
● For HTTP POST, PUT, and DELETE requests, If you expect text data,
the getReader method returns a BufferedReader for you to use to read the
raw data. If you expect binary data, the getInputStream method returns a
15
ServletInputStream for you to use to read the raw data
● A ServletResponse, encapsulates communication from servlet back
to the client.
– Allows servlet to set the content length and MIME type of the reply.
– Provides an output stream, ServletOutputStream, and a Writer
through which the servlet can send the reply data.
– Use the getWriter method to return text data to the user, and the
getOutputStream method for binary data.
16
Get requests - override doGet()
public class BookDetailServlet extends HttpServlet {
18
Post requests - override doPost()
public class ReceiptServlet extends HttpServlet {
19
Session stracking
Mechanism that servlets use to maintain state about a series of
requests from the same user (that is, requests originating from the
same browser) across some period of time.
20
Session tracking - getting the session
22
public class CatalogServlet extends HttpServlet {
Each HTTP request and response header is named and has a single
value. For example, a cookie could be a header named BookToBuy
with a value 304qty1, indicating to the calling application that the
user wants to buy one copy of the book with stock number 304.
(Cookies and their values are application-specific.)
25
To get information from a cookie,
2.Find the cookie or cookies with the name that you are
interested in, using standard programming techniques
26
public void doGet (HttpServletRequest request, HttpServletResponse res
throws ServletException, IOException{
// Check for pending adds to the shopping cart
String bookId = request.getParameter("Buy");
//If the user wants to add a book, remember it by adding a cookie
if (bookId != null) {
Cookie getBook = new Cookie("Buy", bookId);
...
}
// set content-type header before accessing the Writer
response.setContentType("text/html");
// now get the writer and write the data of the response
PrintWriter out = response.getWriter();
out.println("<html>" +
"<head><title> Book Catalog </title></head>" + ...);
... 27
Set cookie attributes
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
//If the user wants to add a book, remember it by adding a cookie
if (values != null) {
bookId = values[0];
Cookie getBook = new Cookie("Buy", bookId);
getBook.setComment("User wants to buy this book " +
"from the bookstore.");
}
...
}
28
Send the cookie
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
//If the user wants to add a book, remember it by adding a cookie
if (values != null) {
bookId = values[0];
Cookie getBook = new Cookie("Buy", bookId);
getBook.setComment("User has indicated a desire " +
"to buy this book from the bookstore.");
response.addCookie(getBook);
}
...
}
29
Retrieving cookies
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
/* Handle any pending deletes from the shopping cart */
String bookId = request.getParameter("Remove");
if (bookId != null) {
// Find the cookie that pertains to that book
Cookie[] cookies = request.getCookies();
for(i=0; i < cookies.length; i++) {
Cookie thisCookie = cookie[i];
if (thisCookie.getName().equals("Buy") &&
thisCookie.getValue().equals(bookId)) {
…..
30
31