我有一个使用Servlet3.0、使用Tomcat7.0.25并将应用程序部署为war(mywebapp.war)的简单web应用程序。
战争结构如下:
mywebapp/index.html
mywebapp/META-INF/MANIFEST.MF
mywebapp/WEB-INF/classes/org/iq/adapter/ServerAdapter.class
index.html

<html>
  <head>
    <title>my web app</title>
  </head>
  <body>
    <h1>Your server is Up and Running</h1>
  </body>
</html>

ServerAdapter.java
package org.iq.adapter;

@WebServlet(name="ServerAdapter", urlPatterns="/adapter/*")
public class ServerAdapter extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        System.out.println(this.getClass()+"::doGet called");
    }

    @Override
    public void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
        System.out.println(this.getClass()+"::doPost called");
    }
}

当我尝试使用以下链接从浏览器访问mywebapp时:
localhost:8080/mywebapp-我得到一个空白屏幕,index.html没有呈现-为什么?我想既然没有提到欢迎文件,因为我没有使用web.xml
localhost:8080/mywebapp/index.html-我得到一个空白屏幕,index.html仍然没有呈现-为什么?我迷路了
localhost:8080/mywebapp/adapter-我得到一个空白屏幕,但是我在服务器控制台上得到的sysout是“class org.iq.adapter.ServerAdapter::doGet called”-正如预期的那样

最佳答案

在web INF文件夹中创建一个web.xml文件,如下所示,并在欢迎文件列表中添加index.html

<?xml version="1.0" encoding="ISO-8859-1" ?>

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

 <welcome-file-list>
   <welcome-file>index.html</welcome-file>
    </welcome-file-list>

  <servlet>
    <servlet-name>ServerAdapter </servlet-name>
    <servlet-class>org.iq.adapter.ServerAdapter </servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>ServerAdapter </servlet-name>
    <url-pattern>/adapter</url-pattern>
</servlet-mapping>
</web-app>

10-05 17:55