Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
22
Chapter 2 First Servlets
Listing 2.1 ServletTemplate.java 
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
      
    // Use "request" to read incoming HTTP headers
    // (e.g. cookies) and HTML form data (e.g. data the user
    // entered and submitted).
    
    // Use "response" to specify the HTTP response status
    // code and headers (e.g. the content type, cookies).
    
    PrintWriter out = response.getWriter();
    // Use "out" to send content to browser
  }
}
Both of these methods take two arguments: an 
HttpServletRequest
 and
an 
HttpServletResponse
. The 
HttpServletRequest
 has methods by
which you can find out about incoming information such as form data, HTTP
request headers, and the client's hostname. The 
HttpServletResponse
 lets
you specify outgoing information such as HTTP status codes (200, 404, etc.),
response headers (
Content Type
, 
Set Cookie
, etc.), and, most importantly,
lets you obtain a 
PrintWriter
 used to send the document content back to the
client. For simple servlets, most of the effort is spent in 
println
 statements
that generate the desired page. Form data, HTTP request headers, HTTP
responses, and cookies will all be discussed in detail in the following chapters.
Since 
doGet
 and 
doPost
 throw two exceptions, you are required to
include them in the declaration. Finally, you have to import classes in
java.io
 (for 
PrintWriter
, etc.), 
javax.servlet
 (for 
HttpServlet
, etc.),
and 
javax.servlet.http
 (for 
HttpServletRequest
 and 
HttpServlet 
Response
). 
Strictly speaking, 
HttpServlet
 is not the only starting point for servlets, since
servlets could, in principle, extend mail, FTP, or other types of servers. Servlets
for these environments would extend a custom class derived from 
Generic 
Servlet
, the parent class of 
HttpServlet
. In practice, however, servlets are
used almost exclusively for servers that communicate via HTTP (i.e., Web and
application servers), and the discussion in this book will be limited to this usage.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved