javascript - 如何在没有 web.xml 的情况下将 AJAX 映射到 servlet

标签 javascript java ajax servlets

TL;DR:将 @WebServlet("/Find-Customers") 放在 servlet(通过 Tomcat 7 部署)的开头不会将 servlet 映射到 host:port/webproject/Find-Customers,即使 servlet 是在 src 文件夹中。

我尝试使用 @WebServlet("/...") 调用 servlet,我过去曾这样做过,但这次出了点问题。我从未使用过 web.xml,但它工作得很好。我在 ajaxFxns.js 中使用了 Ajax POST 方法,并输入“Find-Customers”作为地址,并在 Java 中输入以下内容:

package coreservlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.servlet.annotation.*;

@WebServlet("/Find-Customers")
public class ShowCustomers extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {


response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");

// more code here

}

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}

Firebug 在涉及“/Find-Customers”时显示 404 Not Found,据我所知,这意味着 @WebServlet 函数未正确地将 servlet 映射到 localhost:8080/webproject/Find-Customers。这是目录结构(去掉了不相关的东西):

Webproject
--src
  --coreservlets
    --ShowCustomers.java
--WebContent
  --scripts
    --ajaxFxns.js
  --index.html

当我创建 coreservlets 文件夹时,我是否应该做一些特殊的事情,或者如何在开发人员环境中调试它(我正在使用 Eclipse)? Web.xml 的实现也不是很顺利,这就是为什么我要问如果没有它如何进行。帮助将不胜感激!!

最佳答案

你能展示 Ajax 代码吗? Ajax 调用的 URL 可能存在问题。 例如考虑以下两种情况:

  1. 在 Ajax 调用中使用“/Find-Customers”作为 URL。它将定位类似 localhost:8080/Find-Customers 的 URL,这是不正确的。
  2. 在 Ajax 调用中使用“Find-Customers”作为 URL。它将定位一个类似 : 的 URL。 localhost:8080/webproject/Find-Customers,这是正确的。

Ajax 调用对于您使用下面的 index.html 和 ajaxFxns.js 发布的 ShowCustomers Servlet 工作正常

index.html:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="ISO-8859-1">
        <script type="text/javascript" src="scripts/ajaxFxns.js"></script>
        <title>Ajax post</title>
    </head>
    <body>
    </body>
</html>

ajaxFxns.js:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "Find-Customers", true);
xhttp.send();

关于javascript - 如何在没有 web.xml 的情况下将 AJAX 映射到 servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36145954/

相关文章:

ajax - CJuiDatePicker 验证消息不起作用

javascript - 如何从 Angular 应用程序中的 gulp 任务访问 rootPath 集

javascript - Vuetify - 如何访问表单规则中的数据

java - 我的 Android 应用程序上有 34 个按钮。有什么方法可以避免为每个人编写 onclicklistener 吗?

jquery - 如何在jquery中动态调用url?

javascript - ajax 函数未返回预期输出

javascript - Javascript 重定向不适用于 IFrame,无需 IFrame 也可工作

javascript - Scala.js:使用 addEventListener 向对象添加事件

java - 如何使用intellij正确远程调试pod?

java - Glassfish 过滤器初始化被调用多次