Tuesday, 18 October 2011

HelloWorld Servlet



1) Configure Tomcat 7.0 in your workspace in Eclipse.
    a) Install Tomcat 7.0 from net.
    b) Try to add Tomcat, by using 
           Window->Preferences -> Server->Add->Choose your Tomcat
2) Write your "Hello World Servlet"..
public class HelloWorldServlet extends HttpServlet{ 

  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException,IOException{
 
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  
  pw.println("<html>");
  pw.println("<head><title>Hello World</title></title>");
  pw.println("<body>");
  pw.println("<h1>Hello World</h1>");
  pw.println("</body></html>");
  }
}
3) update web.xml
  <servlet>
  <servlet-name>helloworldservlet
  </servlet-name>
  <servlet-class>com.HelloWorldServlet</servlet-class>
  </servlet>

  <servlet-mapping>
  <servlet-name>helloworldservlet</servlet-name>
  <url-pattern>/helloworld</url-pattern>
  </servlet-mapping>
4) go to browser, and run as following...
 http://localhost:8080/Project_Name/Name_Of_UrlPattern