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

时间:2016-03-22 04:12:01

标签: 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的实现并没有真正顺利进行,这就是为什么我要问如何没有它。帮助将不胜感激!!

1 个答案:

答案 0 :(得分:1)

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

  1. 在Ajax调用中使用“/ Find-Customers”作为URL。它将定位一个URL,如:localhost:8080 / Find-Customers,这是不正确的。
  2. 在Ajax调用中使用“Find-Customers”作为URL。它将定位一个URL,如:。 localhost:8080 / webproject / Find-Customers,这是正确的。
  3. 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();