How to execute java servlet program

Leave a Comment

For obtaining the output of below given servlet, following steps are followed.

Java program []
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
 public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
  PrintWriter out= response.getWriter();
  out.println("<title>My First Servlet</title>");
  out.println("<h1>Hello How are U?</h1>");
  out.println("<h2>I am enjoying this Servlet Application</h2>");
  out.println("<h3>See You later!</h3>");

Step 1: We will first compile it. The servlet can be compiled can be compiled using any of the following two methods.

Method 1: Compile the java servlet code using javac by specifying the class path using following command at the command prompt -
C:\test>javac - classpath
"C:\Tomcat 5.5\apache-tomcat-5.5.27\common\lib\servlet-api.jar"

Note that is the name of my servlet for which I want  I want to obtain the output. The servlet-api.jar file contains all the required interfaces and classes needed for executing the servlet.

Method 2: You can set the CLASSPATH using environment variable as follows.

Then simply type the folllowingcommand at the command propmpt for compiling as -

Step 2: The class file FirstServlet.class gets generated by this method.
Now we will deploy this servlet in the Tomcat. For that, we have to copy the generated class file FirstServlet.class to the directory -
C:\Tomcat 5.5\apache-tomcat-5.527\webapps\servlets-examples\WEN-INF\classes

Step 3: Now open the web.xml file present in the current directory. In my case, I have one web.xml file at the path
C:\Tomcat 5.5\apache-tomcat-5.527\webapps\servlets-examples\WEN-INF

Open this web.xml file in Notepad. Edit it by adding following statements -

Now Start the Tomacat by clicking the startup.bat. Then open some web browser and type the URL :


Post a Comment