[ Team LiB ] |
Recipe 1.1 Writing a ServletProblemYou want to write a servlet that is part of a web application. SolutionCreate a Java class that extends javax.servlet.http.HttpServlet. Make sure to import the classes from servlet.jar (or servlet-api.jar)—you'll need them to compile the servlet. DiscussionA servlet is a Java class that is designed to respond with dynamic content to client requests over a network. If you are familiar with Common Gateway Interface (CGI) programs, then servlets are a Java technology that can replace CGI programs. Often called a web component (along with JSPs), a servlet is executed within a runtime environment provided by a servlet container or web container such as Jakarta Tomcat or BEA WebLogic.
Servlets are installed in web containers as part of web applications. These applications are collections of web resources such as HTML pages, images, multimedia content, servlets, JavaServer Pages, XML configuration files, Java support classes, and Java support libraries. When a web application is deployed in a web container, the container creates and loads instances of the Java servlet class into its Java Virtual Machine (JVM) to handle requests for the servlet.
All servlets implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests. The following basic sequence occurs when the web container creates a servlet instance:
Example 1-1 shows a typical servlet idiom for handling an HTML form. The doGet( ) method displays the form itself. The doPost( ) method handles the submitted form data, since in doGet( ), the HTML form tag specifies the servlet's own address as the target for the form data. The servlet (named FirstServlet) specifies that the declared class is part of the com.jspservletcookbook package. It is important to create packages for your servlets and utility classes, and then to store your classes in a directory structure beneath WEB-INF that matches these package names. The FirstServlet class imports the necessary classes for compiling a basic servlet, which are the emphasized import statements in Example 1-1. The Java class extends HttpServlet. The only defined methods are doGet( ) , which displays the HTML form in response to a GET HTTP request, and doPost( ), which handles the posted data. Example 1-1. A typical HttpServlet used for handling an HTML formpackage com.jspservletcookbook;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter to send text data to the client who has requested the
//servlet
java.io.PrintWriter out = response.getWriter( );
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Help Page</title></head><body>");
out.println("<h2>Please submit your information</h2>");
//make sure method="post" so that the servlet service method
//calls doPost in the response to this form submit
out.println(
"<form method=\"post\" action =\"" + request.getContextPath( ) +
"/firstservlet\" >");
out.println("<table border=\"0\"><tr><td valign=\"top\">");
out.println("Your first name: </td> <td valign=\"top\">");
out.println("<input type=\"text\" name=\"firstname\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("Your last name: </td> <td valign=\"top\">");
out.println("<input type=\"text\" name=\"lastname\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("Your email: </td> <td valign=\"top\">");
out.println("<input type=\"text\" name=\"email\" size=\"20\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
out.println("</table></form>");
out.println("</body></html>");
}//doGet
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
//display the parameter names and values
Enumeration paramNames = request.getParameterNames( );
String parName;//this will hold the name of the parameter
boolean emptyEnum = false;
if (! paramNames.hasMoreElements( ))
emptyEnum = true;
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter to send text data to the client
java.io.PrintWriter out = response.getWriter( );
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Submitted Parameters</title></head><body>");
if (emptyEnum){
out.println(
"<h2>Sorry, the request does not contain any parameters</h2>");
} else {
out.println(
"<h2>Here are the submitted parameter values</h2>");
}
while(paramNames.hasMoreElements( )){
parName = (String) paramNames.nextElement( );
out.println(
"<strong>" + parName + "</strong> : " +
request.getParameter(parName));
out.println("<br />");
}//while
out.println("</body></html>");
}// doPost
}
You might have noticed that doGet( ) and doPost( ) each throw ServletException and IOException. The servlet throws IOException because the response.getWriter( ) (as well as PrintWriter.close( )) method call can throw an IOException. The doPost( ) and doGet( ) methods can throw a ServletException to indicate that a problem occurred when handling the request. For example, if the servlet detected a security violation or some other request problem, then it could include the following code within doGet( ) or doPost( ): //detects a problem that prevents proper request handling... throw new ServletException("The servlet cannot handle this request."); Figure 1-1 shows the output displayed by the servlet's doGet( ) method in a browser. Figure 1-1. The servlet's output for doGet( ) methodFigure 1-2 shows the servlet's output for the doPost( ) method. Figure 1-2. The servlet's output for the doPost( ) methodSee AlsoRecipe 1.3 on compiling a servlet; Recipe 1.4 on packaging servlets and JSPs; Recipe 1.5 on creating the deployment descriptor; Chapter 2 on deploying servlets and JSPs; Chapter 3 on naming servlets; the javax.servlet.http package JavaDoc: http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/package-summary.html; the J2EE tutorial from Sun Microsystems: http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/J2eeTutorialTOC.html; Jason Hunter's Java Servlet Programming (O'Reilly). |
[ Team LiB ] |