1

I'm trying to use Java EE Servlets and connect to them with AJAX. I am using netbeans as my IDE with Glassfish as the server. When the $.get() method is called, I get a 404 error in Chrome's console.

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

}

When I click on the HTML element I get the first alert() fine but then I get a 404 error trying to connect to "http://localhost:8080/cs261-project-war/AJAX_test/NewServlet" Thanks

EDIT: I forgot to mention that all of these files are within my /web/AJAX_test/ folder, and I am on Windows.

EDIT 2: The solutions from the duplicate thread did not fix my issue. For the HTML element solution, my JS url variable was given the value 'undefined' and the global JS solution gave me this url:

http://localhost:8080/cs261-project-war/AJAX_test/$%7BpageContext.request.contextPath%7DNewServlet
Adam Lewis
  • 11
  • 5

0 Answers0