1. 创建一个类servletTest2 继承HttpServlet类。
public class servletTest2 extends HttpServlet { public servletTest2(){ super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
web.xml中增加servlet的定义
<servlet> <servlet-name>servletTest2</servlet-name> <servlet-class>servletTest2</servlet-class> </servlet> <servlet-mapping> <servlet-name>servletTest2</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping>
例如项目名是test,运行tomcat,打开浏览器访问地址:http://127.0.0.1:8080/test/test
显示如下: