Creating Your First Servlet


When a user asks for a page in a browser, he commonly uses the HTTP GET method. This means that the browser asks the server to "get" the item described by the universal resource locator or URL. The corresponding HttpServlet service method is doGet() . This method is called on the servlet by the container when an HTTP GET request is made. You will cover how the container maps a servlet to a URL in a later section.

A doGet() Servlet Example

Listing 17.1 shows a very simple HTTP servlet that displays the parameters of a client request. The example code shows how to use the doGet() method to interact with the browser or other Web-based client.

Listing 17.1 MyFirstServlet.java ”A Servlet to Print Browser Information
 import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MyFirstServlet extends HttpServlet { public void doGet( HttpServletRequest request,     HttpServletResponse response )     throws ServletException, IOException     { // // get a simple way of putting text into the response // ServletOutputStream    out = response.getOutputStream(); // // tell the client (possibly a browser) what type of document is being returned // response.setContentType("text/html"); // // generate the required HTML elements // out.println("<html><head><title>Hello!</title></head><body>" ); // // generate some dynamic content. the method getRemoteHost() on HttpServletRequest // returns the host name (i.e. www.objectmind.com) from where the request came from // out.println( "Welcome " + request.getRemoteHost() + ".<br>" ); // // print out the user agent information from the browser //       out.println( "Your user agent string is " +                     request.getHeader( "User-Agent" ) ); // // finish the html page // out.println( "</body></html>" );     } } 

Adding doPost() to the Servlet

The other commonly used service method is doPost() , which is called via the HTTP POST method. One way that this method could be called is if an HTML form specified "post" as its method, and gave the URL of the servlet as the action; for example, if you had an HTML file that looked like Listing 17.2.

Listing 17.2 formTest.html ”A Form to Post to Your Servlet
 <html> <head> <title>A sample form handled by a servlet</title> <body> <form action="http://localhost:7001/myFirstWebApp/myfirstservlet" method="post">     Please enter your name: <input type="text" name="username">     <input type="submit" value="Submit"> </form> </body> </html> 

This specifies a small HTML form that would send an HTTP POST to the URL http://localhost:7001/myFirstWebApp/myfirstservlet , the same one you used for the doGet() method. The doPost() method of the servlet would be called with the same arguments as the doGet() method. However, an important difference in this example is that you want to get content that the user entered (in this case a text field labeled as "username"). The HttpServlet makes this task extremely easy, as shown in Listing 17.3.

Listing 17.3 MyFirstServlet.java Addition of doPost() Method
 public void doPost( HttpServletRequest request,                     HttpServletResponse response )     throws ServletException, IOException { // // get a simple way of putting text into the response // ServletOutputStream    out = response.getOutputStream(); // // tell the browser what type of document is being returned // response.setContentType("text/html"); // // generate the required HTML elements // out.println("<html><head><title>Hello!</title></head><body>" ); // // generate dynamic content based on the user input. the method getParameter() // on HttpServletRequest returns the value of the named parameter from the // POST request. // out.println( "Welcome to my site " + request.getParameter( "username" ) ); // // finish the html page //     out.println( "</body></html>" ); } 

Notice that you can get the data from the form by calling the getParameter() method on the HttpServletRequest . In this very simple example, the doPost() method is called when the user clicks on the Submit button on the HTML form. The browser packages up the parameters and sends an HTTP POST to the URL specified. It is the responsibility of the HttpServlet to then pull those parameters apart to allow access to them in the servlet.

An important part of the HttpServlet is the HttpServletRequest and the HttpServletResponse . These classes enable the developer to interact with the input and output of the Web stream. HttpServletRequest has methods that parse the HTML data stream and return these values to the caller. This is faster and less error prone than parsing the HTML directly. In our previous example, you called request.getRemoteHost() to return the name of the client that requested this servlet. This information came from the server-side socket connection that the client is using. Obviously, it is much simpler to call this method than have to deal directly with the socket semantics.

Other methods available through HttpServletRequest include the following:

  • getLocale() ” Returns the java.util.Locale of the browser based on the "Accept-Language" HTTP header. This allows easier internationalization based on the language that the browser is using.

  • getCookies() ” Returns an array of all of the javax.servlet.http.Cookie objects that the client sent.

  • getSession() ” An incredibly useful method that helps the servlet developer maintain state across multiple client calls. The servlet container automatically assists with session management by either including cookies in the HttpServletResponse or by using URL rewriting. Either way it insulates the developer from the complex task of maintaining state across multiple invocations of the servlet.

The HttpServletResponse class has methods that do the opposite ”build the HTTP header so that the developers do not have to generate it themselves . The ones used in our previous example, response.setContentType() and response.getOutputStream() , are the two most commonly used.

The setContentType() method enables the developer to tell the browser what kind of content will be returned. Often this is "text/html" for HTML documents, but it can also be any "mime type" that you need. Mime is an abbreviation for Multipurpose Internet Mail Extensions. These are defined methods for how messages are exchanged between two parties. Although they were originally used for electronic mail, they are also used on Web resources to describe them. RFC 2045 has pointers to more information.

The getOutputStream() method gets a javax.servlet.ServletOutputStream that allows the developer to handle the output stream the same way as any other Java stream. Simple println() methods assist in generating output.

Other methods in the HttpServletResponse class include

  • setStatus() ” Enables the developer to set the status that is contained in the HTTP response. This is something like "200" for an OK response.

  • setContentLength() ” Sets the Content-Length field in the HTTP header to the number of bytes in the body of the response message.



BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net