Monday, November 21, 2011

Servlets API

As mentioned earlier, it is the Java Servlet API which is the key to writing Java Web Applications.

Any class which extends the HTTPServlet abstract class can handle web requests.
Any class which extends HTTPServlet becomes a 'Servlet'.

So to make our HelloWorld class a Servlet, extend the HTTPServlet abstract class, as shown below:

 package org.confucius;  
   
 import java.io.IOException;  
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
   
   
 public class HelloWorld extends HttpServlet{  
      public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
      {  
           response.getWriter().println("Hello World!");  
      }  
 }  
   


Implementing the doGet method makes it possible for HelloWorld to receive HTTP requests.

Writing to the response will make the text appear on the browser.

In order for this class to compile, we need the servlet-api.jar

Update your ivy.xml file to get the servlet-api.jar, as shown below:

 <ivy-module version="2.0">  
   <info organisation="org.confucius" module="helloworld"/>  
   <dependencies>  
     <dependency org="javax.servlet" name="servlet-api" rev="2.5"/>  
   </dependencies>  
 </ivy-modu  


If you now run the ant:resolve task, it will download the servlet-api.jar to your /lib

For Eclipse to detect it, right click on HelloWorld project, the go to:
Properties->Java Build Path->Libraries->Add Jars

then add the /lib/servlet-api.jar

Now run the ant:compile task to compile HelloWorld.java

No comments: