一、查看本地的Tomcat版本

二、打开eclipse,新建Dynamic Web project
1、File->New->Other->Web,选择Dynamic Web Project后,点击下一步

2、输入“Project Name”,点击“New Runtime Environment”,新建一个服务运行环境,我安装的是9.0的版本,所以这边选择“Apache Tomcat v9.0”

3、指定Tomcat的路径

三、在新建的Web工程下面新建Servlet,右键New->Servlet

4、在doGet方法中加入以下内容,然后运行(右键Run As->Run on Server)
返回状态码200的例子:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("GBK");
PrintWriter writer = response.getWriter();
writer.print("8081 成功返回200");
}
5、运行过程需要一点时间


6、发现运行出现问题
Several ports (8005, 8081, 8009) required by Tomcat v9.0 Server at localhost are already in use. The server may already be running in another process, or a system process may be using the port. To start this server you will need to stop the other process or change the port number(s).
可能原因:
(1)、端口被占用,去server.xml文件里把端口修改以下即可
(2)、由于我在cmd里输入“startup”,开启了Tomcat服务,关闭后重新运行

7、再次运行,成功后,自动开启浏览器,出现正确结果

四、一个Tomcat服务器里实现2个接口,复制成功的Servlet文件后,@WebServlet("/GetServerDown")括号里的内容要同步修改,否则Tomcat服务器会开启失败。
Server Tomcat v9.0 Server at localhost failed to start.

返回状态码是500的例子:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(5/0);
response.setCharacterEncoding("GBK");
PrintWriter writer = response.getWriter();
writer.print("8081 成功返回500");
}
超时时间设置为2min的例子:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setCharacterEncoding("GBK");
PrintWriter writer = response.getWriter();
writer.print("8081 成功返回超时");
}
五、开启2个Tomcat服务,模拟多个主机情况
步骤:
1、直接复制整个Dynamic Web project工程

2、右键Copy->Paste,编辑复制的服务器,修改三个端口号

这个方法不能用,会以下报错
Could not publish server configuration for Tomcat v9.0 Server at localhost. Multiple Contexts have a path of "/TestServer".

3、复制完工程,运行工程里的一个servlet文件,选择新建Tomcat服务器,然后重命名

4、运行成功后,Modules里的Servers里会多一个服务器,如果再报错,就直接把那个服务器删除,重新运行,新建server,打开查看端口,如果两个是一样的,就修改一下端口号,重新启动就可以了。

5、Tomcat服务成功起来后,在浏览器输入:
“http://localhost:8081/TestServer/HelloServlet”和“http://localhost:8082/TestServer/HelloServlet”,返回正确的结果

网友评论