Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server...

30
Servlets Pranav Maydeo

Transcript of Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server...

Servlets

Pranav Maydeo

What is a Servlet ?

Servlets are modules of Java code that run in a server application to answer client requests.

Servlets are not tied to a specific client-server protocol.

Typical uses for HTTP Servlets include:Processing and/or storing data submitted by an HTML form.

Providing dynamic content, e.g. returning the results of a database query to the client.

Managing state information on top of the stateless HTTP.

Servlets vs CGI

• A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.

• A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.

• There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.

Basic Servlet Architecture

• init()

• service()

• destroy()

The Servlet Life Cycle

Servlets Step by Step• 1: import java.io.*;

• 2: import javax.servlet.*;• 3: import javax.servlet.http.*; • 4: public class HelloClientServlet extends HttpServlet {• 5: protected void doGet(HttpServletRequest req, HttpServletResponse res) • 6: throws ServletException, IOException {• 7: res.setContentType("text/html");• 8: PrintWriter out = res.getWriter();• 9: out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>"+• 10: "</HEAD><BODY>Hello Client!</BODY></HTML>");• 11: out.close();• 12: } • 13: public String getServletInfo() {• 14: return "HelloClientServlet 1.0";• 15: }• 16: }

Providing Servlet Information• Some applications can get descriptive information from the

servlet and display it. The servlet description is a string that can describe the purpose of the servlet, its author, its version number, or whatever the servlet author deems important.

The following example shows the description of the BookStoreServlet:

• public class BookStoreServlet extends HttpServlet {

• ...• public String getServletInfo() {• return "The BookStore servlet returns

this " + ”Description about the Bookstore.";• }• }

Session Tracking

• Session tracking is a 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.

• 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).

Obtaining a Session• The getSession method of the HttpServletRequest

object returns a user's 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();

}

}

Storing and Getting Data from a Session

• 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.

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

}

}

}

Invalidating the Session

• A user's session can be invalidated manually or, depending

on where the servlet is running, automatically. • To manually invalidate a session, use the session's invalidate method. Some applications have a natural point at which to invalidate the session.

session.invalidate();

Using Cookies

• 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.)

• Multiple cookies can have the same name. For example, a servlet could send two cookies with headers named BookToBuy; one could have the value shown previously, 304qty1,while the other could have a value 301qty3. These cookies would indicate that the user wants to buy one copy of the book with stock number 304, and three copies of

the book with stock number 301. • In addition to a name and a value, you can also provide

optional attributes such as comments. Current web browsers do not always treat the optional attributes correctly, so you should not rely on them.

• A server can provide one or more cookies to a client. Client software, such as a web browser, is expected to support twenty cookies per host, of at least four kilobytes each .

A sample cookie

• Cookie:[email protected]

• MC1V=2&GUID=C3BEDC1552C1431C8DC9B0326A4B22E2msn.com/0304938803229592233428380598429311696*

Using cookies...

• To send a cookie,

– Instantiate a Cookie object

– Set any attributes

– Send the cookie

• To get information from a cookie,

– Retrieve all the from the user's request

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

– Get the values of the cookies that you found

Instantiating

• public void doGet (HttpServletRequest request,• HttpServletResponse response)• 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);• ...• }• }

Setting 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.");

• } …

• }

Sending 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);

• } …

• }

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 the book to remove

• Cookie[] cookies = request.getCookies(); ...

• // Delete the book's cookie by setting its maximum age to zero thisCookie.setMaxAge(0);

• }

Getting Values• 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);

• } } }

Inter-Servlet Communication

• Servlets have access to other Servlets in the same Servlet Context (usually a Servlet directory), represented by an instance of javax.servlet.ServletContext.

• The ServletContext is available through the ServletConfig object's getServletContext method.

• A Servlet can get a list of all other Servlets in the Servlet Context by calling getServletNames on the

ServletContext object.

Inter-Servlet Communication

• A servlet can call another servlet's public methods

directly, if the two servlets run within the same server. To call another servlet's public methods directly, you must:

• Know the name of the servlet that you want to call.

• Gain access to that servlet's Servlet object.

• Call the servlet's public method.

• public class BookDetailServlet extends HttpServlet {

• public void doGet(HttpServletRequest request,• HttpServletResponse response)• throws ServletException, IOException• {• ...• BookDBServlet database =

(BookDBServlet) getServletConfig().getServletContext().getServlet("bookdb");

• BookDetails bd = database.getBookDetails(bookId);• ...• }• }

Dispatching Requests

• An object implementing the RequestDispather interface may be obtained from the ServletContext via the following methods:

• � getRequestDispatcher• � getNamedDispatcher

• The getRequestDispatcher method takes a String argument describing a path within the scope of the ServletContext. This path must be relative to the root of the ServletContext. This path is used to look up a servlet, wrap it with a RequestDispatcher object, and return it.

• The getNamedDispatcher method takes a String argument indicating the name of a servlet known to the ServletContext. If a servlet is known to the ServletContext by the given name, it is wrapped with a RequestDispatcher object and returned.

Using a Request Dispatcher

• To use a request dispatcher, a developer needs to call either the include or forward method of the RequestDispatcher interface using the request and response arguments that were passed in via the service method of the Servlet interface.

include

• The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the response object as well as the ability to commit a response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface.

• The included servlet cannot set headers or call any method that affects the headers of the response. Any attempt to do so should be ignored.

forward

• The forward method of the RequestDispatcher interface may only be called by the calling servlet if no output has been committed to the client.

• If output exists in the response buffer that has not been committed, it must be reset (clearing the buffer) before the target servlet’s service method is called.

• If the response has been committed, an IllegalStateException must be thrown.

Thanks !!