Anda di halaman 1dari 31

Java Servlets

● Servlets : programs that run within the context of a server,


analogous to applets that run within the context of a browser.
● Used to implement a service easily and efficiently.
– Easily: programmer may take advantage of support provided by
Java Web Server:
● parsing HTTP requests
● handling connections to Web clients.
– Efficiently, run as separate light weight threads of the Java
Server process rather than separate heavy weight processes
● load and execute much faster than CGI programs.
● Servlets are part of a larger Java Server Architecture.
– first implemented in a server built by Sun that was called
Jeeves, later renamed the Java Web Server
java.sun.com/products/java_server/webserver.
1
● Servlets are protocol- and platform-independent server-side
components, written in Java, to dynamically extend Java-enabled
servers.
– run inside servers, don’t need a GUI.
– downloaded on demand to system that requests them.

put Java Server


Client 1
-Applet
Call Servlet

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.*;

public class MyServlet extends GenericServlet {


public void service (
ServletRequest request,
ServletResponse response
) throws ServletException, IOException
{
...
}
}
6
Servlet model
● The service method is provided with Request and Response
parameters.
– Servlets retrieve data through an input stream, and send
responses using an output stream:

● ServletInputStream in = request.getInputStream ();


● ServletOutputStream out = response.getOutputStream ();

● 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:

● Have instance-specific data

● Encapsulate user sessions


– each servlet instantiated inside server is a separate entity

● Can access environment through servletcontext object


– allow inter-servlet sharing of data

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.

● Closing the Writer or ServletOutputStream after you send the


response allows the server to know when the response is complete.

● ServletRequest and ServletResponse are interfaces defined by the


javax.servlet package.

16
Get requests - override doGet()
public class BookDetailServlet extends HttpServlet {

public void doGet (HttpServletRequest request,HttpServletResponse response)


throws ServletException, IOException{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html>" + "<head><title>Book Description</title></head>" + ...);
//Get the identifier of the book to display
String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
17
}
doGet()
● SnoopServlet - shows request parameters

18
Post requests - override doPost()
public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// then write the response
out.println("<html><head><title> Receipt </title>" + ...);
out.println("<h3>Thank you for purchasing your books from us " +
request.getParameter("cardname") +
...);
out.close();
}
...

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.

Sessions are shared among the servlets accessed by a client. To use


session tracking

• Get a session (an HttpSession object) for a user.



• Store or get data from the HttpSession object.

• Invalidate the session (optional).

20
Session tracking - getting the session

public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
...
out = response.getWriter();
...
}
}
21
Session tracking - getting state
The HttpSession interface provides methods that store and return:

•Standard session properties, such as a session identifier


•Application data, which is stored as a name-value pair, where
the name is a String and the value is an object
•Use naming conventions to avoid servlets accidentally overwriting
each other's values in the session.
•servletname.name where servletname is the full name of the
servlet, including its packages.
•com.acme.WidgetServlet.state is a cookie with the
servletname com.acme.WidgetServlet and the name state.

22
public class CatalogServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Get the user's session and shopping cart
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getValue(session.getId());

// If the user has no cart, create a new one


if (cart == null) {
cart = new ShoppingCart();
session.putValue(session.getId(), cart);
}
...
}
}
23
Because an object can be associated with a session, the Duke's Bookstore
example keeps track of the books that a user has ordered within an object.
The object is type ShoppingCart and each book that a user orders is
stored in the shopping cart as a ShoppingCartItem object. For example, the
following comes from further down in the doGet method of the CatalogServlet:
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
ShoppingCart cart = (ShoppingCart)session.getValue(session.getId());
...
// Check for pending adds to the shopping cart
String bookId = request.getParameter("Buy");
//If the user wants to add a book, add it and print the result
String bookToAdd = request.getParameter("Buy");
if (bookToAdd != null) {
BookDetails book = database.getBookDetails(bookToAdd);
cart.add(bookToAdd, book);
out.println("<p><h3>" + ...);
}
} 24
Cookies are a way for a server (or a servlet, as part of a server) to
send some information to a client to store, and for the server to later
retrieve its data from that client. Servlets send cookies to clients by
adding fields to HTTP response headers. Clients automatically return
cookies by adding fields to HTTP request headers.

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,

1.Retrieve all the cookies from the user's request

2.Find the cookie or cookies with the name that you are
interested in, using standard programming techniques

3.Get the values of the cookies that you found

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)) {

// Delete the cookie by setting its maximum age to zero


thisCookie.setMaxAge(0);
}
}
}

…..
30
31