使用jQuery的Java Servlet Ajax 404错误

时间:2017-02-28 14:55:21

标签: java jquery ajax servlets http-status-code-404

我正在尝试使用Java EE Servlet并使用AJAX连接它们。我使用netbeans作为我的IDE与Glassfish作为服务器。当调用$ .get()方法时,我在Chrome控制台中收到404错误。

HTML:

<html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <script src="ajax-test.js"></script>
</head>
<body>
    <div id="click-me">TODO write content</div>

</body>
</html>

使用Javascript:

$(document).ready(function(){
    $("#click-me").click(function() {
        alert("about to $.get");
        $.get("NewServlet", function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
});

Java Servlet:

package AJAX_test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "NewServlet", urlPatterns = {"/NewServlet"})
public class NewServlet extends HttpServlet {

    private ServletContext context;

    @Override
    public void init(ServletConfig config) throws ServletException {
        this.context = config.getServletContext();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String text = "some text";

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(text);
    }

    //doPOST and stuff goes here

}

当我点击HTML元素时,我得到了第一个alert(),但是在尝试连接到“http://localhost:8080/cs261-project-war/AJAX_test/NewServlet”时出现404错误 感谢

编辑:我忘了提及所有这些文件都在我的/ web / AJAX_test /文件夹中,我在Windows上。

编辑2:来自重复线程的解决方案无法解决我的问题。对于HTML元素解决方案,我的JS url变量的值为'undefined',全局JS解决方案给了我这个url:

http://localhost:8080/cs261-project-war/AJAX_test/$%7BpageContext.request.contextPath%7DNewServlet

0 个答案:

没有答案