Creating and Executing Servlet


The following are the steps for creating and executing a servlet in eclipse IDE.




  • Select File > New > Project. Then New Project window will pop up, select Tomcat Project then click Next button.





  • In the New Tomcat Project window, input the project name, here use "ServletDemo",then click Next button.





  •   To make it simple, keep this as default and click Finish button.






  •   Select WEB-INF/src in workspace and right click it and select  New > File.






  • In the pop up window New File, input file name "SimpleServlet.java" and click Finish button.





  •   Input the following code in to the file SimpleServlet.java and click Save button in toolbar.



import java.io.PrintWriter;


import javax.servlet.*;




public class SimpleServlet extends javax.servlet.http.HttpServlet {

public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {

    performTask(request, response);

   }

 


public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

throws javax.servlet.ServletException, java.io.IOException {

   performTask(request, response); }


 

public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)

{

    try

   {

       response.setContentType("text/html");

       PrintWriter out = response.getWriter();

       out.println("This is a Simple Servlet Demo");

    }catch(Throwable theException){

       theException.printStackTrace();

    }

 }

}



  • Select WEB-INF/ in workspace and right click it and select  New > File.





  • A New File window will pop up and input the file name "web.xml" and click Finish button.





  •  Input the following contentinto the file web.xml.


 <?xml version="1.0" encoding="UTF-8"?> 

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>

    <servlet>

                <servlet-name>SimpleServlet</servlet-name>

                <servlet-class>SimpleServlet</servlet-class>

    </servlet>

    <servlet-mapping>

                <servlet-name>SimpleServlet</servlet-name>

                <url-pattern>/SimpleServlet</url-pattern>

    </servlet-mapping>

</web-app>



  • Press the Start Tomcat button in tool bar, after tomcat starts, open a browser and input the URL: http://localhost:8080/ServletDemo/SimpleServlet . The result will show as below:


                    

Copyright © 2012 VisualBuilder. All rights reserved