Servlet creation and mapping

Create servlet program which is extending HttpServlet.

package com.gj; import; import; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); Date date = new Date(); writer.println("<html>"+"<body>"+"<h5><Servlet></h5> <"+date+"></body>"+"</html>"); } }

We need to define mappings by using web.xml file.

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>myservlet</servlet-name> <servlet-class>com.gj.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/serv1</url-pattern> </servlet-mapping> </web-app>

The hierarchy of the servlets that is deployment must be in the following manner

Hierarchy of servlet.jpg

Tomcat expects this hierarchy (i.e.) the above pattern:

All the classes should be deployed under WEB-INF/classes under tomcat webapps folder.

Deployed folder

Note: Whenever you modify servlet source code, then you should redeploy those modified servlet classes into WEB-INF folder and restart the tomcat.

HTML Comment Box is loading comments...