Google
 

 

up previous next contents
Up: 3. Day 3: Standard Previous: 3.11 Servlets and JSPs Next: 3.13 JavaServer Pages   Contents

Subsections

3.12 Servlets

3.12.1 Objectives

  • Understand servlet framework.
  • Write basic servlets.

3.12.2 Servlet basics

  • Used to deliver dynamic content to web pages.
  • Request
  • Response
  • GET and POST
  • The servlet API
  • Request, service(), doGet()/doPost(), response.

3.12.3 HelloWorldServlet

  • A sample HelloWorldServlet:
      import java.io.*;
      import javax.servlet.*;
      import javax.servlet.http.*;
      public class HelloWorldServlet extends HttpServlet 
      {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
        {
          resp.setContentType("text/html");
          PrintWriter out = response.getWriter();
          out.println("<html><body>Hello, world</body></html>");
          out.close();
        }
      }
    

3.12.4 Servlet lifecycle

  • Handled by the servlet container.
  • Create and initialize the servlet.
  • Handle zero or more service calls.
  • Destroy and garbage collect the servlet.
  • A single servlet instance to handle every request.

3.12.5 HTTPServlet

  • Override doGet() to handle GET requests.
  • Override doPost() to handle POST requests.
  • Both methods take HTTPServletRequest and HTTPServletResponse as arguments.
  • A few other methods, but used much less often - doDelete, doTrace, doOptions, doPut

3.12.6 HTTPServletRequest

  • getMethod()
  • getQueryString()
  • getRemoteHost()
  • getRemoteAddr()
  • getAuthType()
  • getContentType()

3.12.7 HTTPServletResponse

  • getWriter()
  • setContentType()
  • getOutputStream()