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 可能存在问题。 例如考虑以下两种情况:
- 在 Ajax 调用中使用“/Find-Customers”作为 URL。它将定位类似 localhost:8080/Find-Customers 的 URL,这是不正确的。
- 在 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/