Wednesday, May 25, 2011

Creating a Servlet without using IDE

Hi,

It is my first blog. My heart felt apologies for the mistakes in the blog
I am demonstrating a program to manually create and run a servlet. I hope the reader is aware of core java. So here we go..
We need following stuff for this :

1.JDK 1.5 or latest version, ( I am here using JDK 1.6)
2. Apache Tomcat (Here we are using Apache Tomcat 6.0.32)

The Following is the code for the TestServlet.java. It simply sends the message to the browser.
I apologise if the code here is not well managed, because i am not so handy with blogging.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throw IOException,ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Test Servlet ");
}

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



After this we need to put the information about our servlet in the web.xml file. Here is what you have to do.

compile your TestServlet.java and put the class file in the following location Apache Software Foundation\apache-tomcat-6.0.32\webapps\examples\WEB-INF\classes

Now update the file web.xml at location Apache Software Foundation\apache-tomcat-6.0.32\webapps\examples\WEB-INF with following information

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>



The above information maps our servlet class to a URL Pattern , Apache tomcat picks your class file this way.
Voila!!. You have just created a servlet. Now we need to start the tomcat server.

After starting the server, type the url : http://localhost:8080/examples/test

You will see the message on the browser, that we put in the servlet.

if this blogs need any modification, your views are always welcomed.
Ravi

No comments:

Post a Comment