Servlet and Forms


Hello World Servlet

With the configuration information out of the way, let's examine how to write a simple servlet (Hello World) and host it under Resin. Consider the following code:

 package example; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet {   public void doGet(HttpServletRequest request,                     HttpServletResponse response)     throws ServletException, IOException {     response.setContentType("text/html");     PrintWriter out = response.getWriter();     out.println("<title>Hello, World!</title>");     out.println("<h1>Hello, World!</h1>");   } } 

When writing a servlet, keep in mind that the class must extend HttpServlet. The HttpServlet class includes four important methods, which can be overridden:

  • init()— Called when the servlet is first instantiated.

  • destroy()— Called when the servlet is removed by the server.

  • doGet()— Called when an HTTP GET request needs to be handled.

  • doPost()— Called when an HTTP POST request needs to be handled.

For our Hello World example, only the doGet() method needs to be overridden; there is nothing to instantiate or destroy, and the POST request won't be used. When the doGet() method is executed, the system passes in the Request and Response objects. The Request object isn't used in this example.

The first statement in the doGet() method sets the response type of the Response object to text/html; it's always a good idea to explicitly set the return type. Next, we obtain a PrintWriter object from the response in order to write HTML to be presented to the client browser. The println() method of the Out object is used to write appropriate HTML to the browser.

By itself, the servlet cannot do much without being configured into the server. First, the source code for the servlet is placed in the /hello/WEB-INF/classes directory. We expect to browse to the URL http://local-host:8080/hello, which in turn will launch our servlet.

In the resin.conf file, you need to add a default <web-app> with an id attribute set to the /hello directory:

 <web-app xmlns=http://caucho.com/ns/resin" > 

You could add all of the servlet-specific elements to this <web-app> element, but it's cleaner to create a web.xml file with the following content:

 <web-app xmlns="http://caucho.com/ns/resin">   <servlet servlet-name='helloworld'            servlet-class='example.Hello'>   </servlet>   <servlet-mapping url-pattern='/hello'                    servlet-name='helloworld'/> <web-app> 

Place the web.xml file in the WEB-INF directory. Once the servlet is located in the directory and you've configured it, a browser can be used to activate the servlet using the URL listed in the code. The browser makes an HTTP GET request, which calls the doGet() method. (If the browser were to use an HTTP POST request instead of GET, the response from the servlet would be nothing since we didn't override the default doPost() method.)

It just so happens that the code to handle a GET request and a POST request is the same for most servlets. Because of this similarity, servlets should include both the doGet() and doPost() methods. The traditional format is to write the servlet code within the doGet() method and have the doPost() method simply call doGet(). For example:

   public void doPost(HttpServletRequest request,     HttpServletResponse response)     throws ServletException, IOException {     doGet(request, response);   } 

Using init Parameters

In our Hello World example, the Hello, World! text is compiled into the code and can be changed only by recompiling the servlet. We can use the <init-param> element to pass values into the servlet. Consider the following web.xml file:

 <web-app>   <servlet servlet-name='helloworld'            servlet-class='example.Hello'>     <init-param text="Hi All" />   </servlet>   <servlet-mapping url-pattern='/hello'                    servlet-name='helloworld'/> </web-app> 

This web.xml includes an <init-param> element with a key of text and a value of "Hi All". To utilize the init parameter, use the servlet's init() method:

 package example; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet {   private String outputText;   public void init() {      outputText = getInitParameter("text");   }   public void doGet(HttpServletRequest request,                     HttpServletResponse response)     throws ServletException, IOException {     response.setContentType("text/html");     PrintWriter out = response.getWriter();     out.println("<title>" + outputText + "</title>");     out.println("<h1>" + outputText + "</h1>");   }   public void doPost(HttpServletRequest request,     HttpServletResponse response)     throws ServletException, IOException {     doGet(request, response);   } ) 

This code includes the init() function for obtaining the parameter defined in the web.xml file. The code in the init() function uses the getInitParameter(String) method and the appropriate key string to pull the value stored in the file. In our case, the text key is passed to the method, which returns the Hi All text to the code. The string is saved in an object variable for later use. At this point, no requests have been made of the servlet but it has been fully initialized.

When either an HTTP GET or POST request comes through to the servlet, the text from the configuration file is output to the browser. Using the same technique as shown in this code, you can add any number of init parameters to the web.xml file.




Mastering Resin
Mastering Resin
ISBN: 0471431036
EAN: 2147483647
Year: 2002
Pages: 180

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