Thursday, June 7, 2012

Servlet 3.0 Program on Tomcat 7.0


Here, I have developed sample project with version 3 servlet on Tomcat server.

Folder Structure:
Tomcat -- > webapps -- > sample -- > WEB-INF -- > classes
Now just write a servlet class using servlet 3.0 standards like MyServlet.java.

My Servlet.java:
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/myServlet")
public class MyServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;

      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            PrintWriter out = response.getWriter();
            out.print("Welcome to Servlet World!!!");
      }
}

Optional :Copy the following web.xml file into WEB-INF folder. It is optional as we are not using application level settings.

web.xml    
<xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
</web-app>

Compile the MyServlet.java and copy the class files in classes folder.
Now start the tomcat server with startup.bat located in tomcat/bin folder and wait for startup.
Now enter the following address to see the result of our servlet.
http://localhost:8080/sample/myServlet                                                                                                           

No comments:

Post a Comment