In this tutorial, we will create a simple servlet saying “Hello World!” with Apache Tomcat v7.0.37.
cd hello mkdir WEB-INF cd WEB-INF mkdir classes
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<HTML>"); out.println("<BODY>"); out.println("Hello World !!!"); out.println("</HTML>"); out.println("</BODY>"); } }
javac -cp [your tomcat]/lib/servlet-api.jar HelloServlet.java
<web-app> <servlet> <servlet-name>HelloServletName</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServletName</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>