jQuery Ajax调用未达到servlet

Jus*_*tin 6 javascript java ajax jquery

我正在尝试进行简单的ajax调用。无论我做什么,它总是执行错误块。我在doPost中有一个从未被击中的sysout。有人告诉我我做错了。这是我的代码。

javascript ----

$.ajax({
    url: "GetBulletAjax",
    dataType: 'json',
    success: function(data) {
        alert("success");
    },
     error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR+" - "+textStatus+" - "+errorThrown);
    }       
}); 
Run Code Online (Sandbox Code Playgroud)

Java ----

public class GetBulletAjax extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public GetBulletAjax() {
        super();
    }

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("made it to servlet");
        PrintWriter out = response.getWriter(); 
        User user = (User) request.getSession().getAttribute("user");
        int userId = user.getId();
        List<Bullet> bullets;

        BulletDAO bulletdao = new BulletDAOImpl();
        try {
            bullets = bulletdao.findBulletsByUser(userId);
            Gson gson = new Gson();
            String json = gson.toJson(bullets);
            System.out.println(json);
            out.println(json);
            out.close();

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }

}
Run Code Online (Sandbox Code Playgroud)

web.xml ----

<servlet>
    <servlet-name>GetBulletAjax</servlet-name>
    <servlet-class>bulletAjax.GetBulletAjax</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetBulletAjax</servlet-name>
    <url-pattern>/GetBulletAjax</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

Dav*_*ter 5

您的客户的网址是什么?您的URL将是相对的-因此,如果页面的URL是相对的,则<server>/foo/bar.htmlajax请求将转到<server>/foo/GetBulletAjax。但是您的servlet定义是<server>/GetBulletAjax

url您的ajax请求更改为/GetBulletAjax。您需要使用前导斜杠来告诉浏览器资源位于站点根目录之外。