1.建立web项目

  前提是在Eclipse中配置好tomcat,Eclipse中配置tomcat请参考Eclipse中tomcat的配置

1)创建dynamic web project,只需要命名为web01_exec,其余默认设置即可;

2)next-next-勾选generate web.xml deployment description,该选项会在目录下生成一个默认的xml文件;

3)在java resource的src下建立命名为web的package,创建名为DateServlet的类;

4)DateServlet类继承自HttpServlet,重载HttpServlet的service方法;

 1 package web;
 2 import javax.servlet.ServletException;
 3 import javax.servlet.http.HttpServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 import java.util.Date;
 8 import java.io.IOException;
 9 import java.io.PrintWriter;
10 public class DateServlet extends HttpServlet {
11     public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
12         Date date=new Date();
13         response.setContentType("text/html");
14         PrintWriter out=response.getWriter();
15         out.println("now:"+date);
16         out.close();
17     }
18 }

 

5)修改web.xml的配置,绿色部分为需要自己添加的<servlet><servlet-mapping>,其中servlet-name为servlet的命名,对应写的类,<servlet>和<servlet-mapping>成对出现,定义访问的路径;

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 3   <display-name>web01_exec</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <servlet>
13       <servlet-name>dateServlet</servlet-name>
14       <servlet-class>web.DateServlet</servlet-class>
15   </servlet>
16   <servlet-mapping>
17       <servlet-name>dateServlet</servlet-name>
18       <url-pattern>/date</url-pattern>
19   </servlet-mapping>
20 </web-app>

 

2.将项目web01_exec加载到tomcat server,(可以直接把项目拖动到tomcat的图标上),启动;

3.localhost:8080/web01_exec/date访问,可以显示当前日期。

版权声明:本文为mosese原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/mosese/p/4558776.html