我正在尝试在Eclipse中创建一个新的动态Web项目。我添加了一个servlet和一些基本的html代码以使其启动并运行。但是我有一个问题。当我使用网址“ / news”通过jquery发出get请求时,出现404 not found错误。

$.get( // resulting url http://localhost:8080/news
  "/news",
  function(data) {
    alert('page content: ' + data);
  }
, "html");


当我检查完整的请求URL时,看到http://localhost:8080/news。之所以有意义,是因为项目名称也应包含在url中。因此,当我将“ project-name / news”传递到get请求中时,我仍然收到404 not found错误。

$.get( // resulting url http://localhost:8080/project-name/project-name/news
  "project-name/news",
  function(data) {
    alert('page content: ' + data);
  }
, "html");


这次,完整的请求URL显示为http://localhost:8080/project-name/project-name/news ...当我手动向http://localhost:8080/project-name/news发出请求时,它的运行正常。那么,为什么eclipse将项目名称添加到url中?

Servlet声明

<servlet>
  <servlet-name>NewsServlet</servlet-name>
  <servlet-class>com.crosbygames.servlet.NewsServlet</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>NewsServlet</servlet-name>
  <url-pattern>/news</url-pattern>
</servlet-mapping>

最佳答案

当您在请求URL中以“ / news”开头时,它将以http://localhost:8080/news开头。

但是,如果您使用“新闻”(不使用斜杠“ /”),它将以http://localhost:8080/<content path>/news开头。

在您的情况下,您在请求URL中使用project-name/news,则结果URL将为http://localhost:8080/project-name/project-name/news,其中project-name是示例中的上下文路径。

09-27 00:16
查看更多