1

I am trying to make HTTP POST request to a spring controller with a json array. I am getting a 404 response. I have gone through the following tutorials:

But no matter what I try, I always get the same error. I am using Spring v3.0.5 for my project.

"NetworkError: 404 Not Found -
http://127.0.0.1:8080/projectmvc/arttestresults/addsearchqueries"

My jQuery code is given below:

$.ajax({
    url: '/projectmvc/arttestresults/addsearchqueries',
    type: 'POST'
    context: document.body,
    dataType: 'json',
    data: {'searchQueries': JSON.stringify([{'appName': 'myAppName', 'searchQuery': 'query # 1'}]}
}).done(function(data) {
    var dataObject;
    try {
        dataObject = jQuery.parseJSON(data);
    } catch (err) {
        dataObject = data;
    }
    // HTML escape.
    // See https://github.com/janl/mustache.js/blob/master/mustache.js#L52
    var entityMap = {
        "&": "&",
        "<": "&lt;",
        ">": "&gt;",
        '"': '&quot;',
        "'": '&#39;',
        "/": '&#x2F;'
    };

    var escapeHtml = function(input) {
        return String(input).replace(/[&<>"'\/]/g, function (s) {
            return entityMap[s];
        });
    };

    // Messages
    $('#message').text('Success');

 }).fail(function(jqXhr, textStatus, errorThrown) {
    $('#message').text('Error');
});

My controller code:

@RequestMapping(method=RequestMethod.POST, value="/arttestresults/addsearchquery")
@ResponseStatus(HttpStatus.OK)
public void  addSearchQuery(HttpServletRequest request) {
  String searchQueryString = request.getParameter("searchQueries");
  Gson gson = new Gson();
  Type collectionType = new TypeToken<List<ArtSearchQueryRequest>>(){}.getType();
  List<ArtSearchQueryRequest> searchQueries =
       gson.fromJson(searchQueryString,    collectionType);
  // Insert the search queries
}

Controller function that renders the JSP

  @RequestMapping(method=RequestMethod.GET, value="/arttestresults/showaddsearchqueryform.html")
  public String showAddSearchQuery(Model model) {
    ArtSearchQueryRequest request = new ArtSearchQueryRequest();
    request.setAppName(APPNAME);
    model.addAttribute("searchQueryRequest", request);
   return "addsearchqueries";
  }

JSP page

<!DOCTYPE html>
<html>
 . . . 
</head>
<body>
<div class="container">
  <div id="message" class="units-2 column" style="left:50%; top: 5%; position:fixed">
  </div>
  <div class="column-group">
      <div class="units-2 column">
        <h4>Add Search Queries</h4>
      </div>
  </div>
  <!-- Add the form inside this. -->
  <div class="column-group">
      <div class="units-2 column">
        <form modelAttribute="searchQueryRequest" method="POST"
         action="${pageContext.request.contextPath}/arttestresults/addsearchquery">
        <div class="form-group">
      <label for="appNameHidden" class="hide">App Name</label>
      <form:hidden path="appName" id="appNameHidden" htmlEscape="true"></form:hidden>
    </div>
          <div class="form-group">
            <label for="searchQuery">Search Query</label>
            <input type="text" maxlength="100"name="searchQuery"
             placeholder="Enter your search query here.">
             <span><a href="#">Add more queries.</a></span>
          </div>
          <button class="button" type="button">Submit</button>
        </form>
      </div>
  </div>
</div>
 <%@ include file="/WEB-INF/views/scripts.jsp" %>
 <script type="text/javascript">
    $('form button').on('click.submit.queries', function(event) {
      event.preventDefault();
      $('form input[type=text]').makeSearchCall({
         url: '${pageContext.request.contextPath}/arttestresults/addsearchqueries',
         type: 'POST',
         appName: 'crawler'
      })
    });
 </script>
</body>
</html>

The request never reaches the controller.

UPDATE The log is as follows:

POST http://localhost:8080/projectmvc/arttestresults/addsearchquery 404 Not Found 5ms
NetworkError: 404 Not Found - http://localhost:8080/projectmvc/arttestresults/addsearchquery"

I tried request mapping with request body as shown below

@RequestMapping(method=RequestMethod.POST, value=arttestresults/addsearchquery)
@ResponseStatus(HttpStatus.OK)
public void  addSearchQuery(@RequestBody final String requestBodyString) {
  String searchQueryString = request.getParameter("searchQueries");
  Gson gson = new Gson();
  Type collectionType = new TypeToken<List<ArtSearchQueryRequest>>(){}.getType();
  List<ArtSearchQueryRequest> searchQueries =
       gson.fromJson(searchQueryString,    collectionType);
  // Insert the search queries
}

UPDATE # 2 Http Fox Post Request returns the following

data: "[{"appName":"crawler","searchQuery":"test1"},{"appName":"crawler","searchQuery":"test2"},{"appName":"crawler","searchQuery":"test3"},{"appName":"crawler","searchQuery":"test4"}]" 
halfer
  • 19,824
  • 17
  • 99
  • 186
Kartik
  • 2,541
  • 2
  • 37
  • 59
  • Does your controller have a class level `@RequestMapping("/projectmvc/**")` annotation? If not, then your request to "/projectmvc/arttestresults/addsearchquery" will never work because your method level `@RequestMapping(method=RequestMethod.POST, value="/arttestresults/addsearchquery")` doesn't include the `/projectmvc/` path. – Patrick Grimard Sep 29 '14 at 19:22
  • Do I need to that? I never had to define the webapp context for other controllers that did not use jQuery Ajax – Kartik Sep 29 '14 at 20:17
  • try your POST request without that path, does it still return a 404? – Patrick Grimard Sep 29 '14 at 21:00
  • Yes. It does. I am not sure why. – Kartik Oct 02 '14 at 01:57
  • Is it your actual code? `@RequestBody` is misspelled, value in the mapping should be in quotes and the should be `/` before `arttestresults` ... The application should not even start... – jny Oct 02 '14 at 13:49
  • Yes. This was my actual code. – Kartik Oct 02 '14 at 20:49

4 Answers4

0

When trouble shooting 404 errors I usually following steps:

  1. Use browser debugger to see the request and data sent in the request
  2. If the request and data is what I am expecting I check the server logs. Usually it gives you an idea what is going on. Usually it is one of the following:

    • Error during application startup which causes mappings not being loaded
    • Incorrect servlet mapping in web.xml
    • annotations are not enabled or not configured correctly
    • Incorrect mapping in controller. To see the mappings turn on the DEBUG mode for Spring logging - it will log all the mappings on the application startup
    • Exception thrown by Spring during request processing and validation.

    Most of these are easily gleaned from the logs. To avoid hitting issues with controller mappings I use Spring MockMVC for unit-testing of controllers - it is much easier to debug issues that way.

    If everything else fails, I turn on the debugger and see what exactly happens.

jny
  • 8,007
  • 3
  • 37
  • 56
0

The data that you send in the AJAX request is an array of objects. But the @RequestBody maps to a String - not sure if this is correct.

I have seen exceptions thrown in the json mapping layer wrapped as 404 errors. The best way to find out the actual exception would be to add the related spring sources(spring web and webmvc should be enough I think), add some breakpoints and debug.

kinf1
  • 89
  • 9
0

@RequestMapping(value = "/something", headers = "Accept=application/json", method = RequestMethod.POST)

dikkini
  • 1,184
  • 1
  • 23
  • 52
-1

If spring security is used in your project, then you should add csrf token in your ajax request. This answer contains detailed information.

  • 1
    I would request you to understand the details posted in question and propose solution that relates specifically to the problem faced by the user asking question. – Vishal Shukla Feb 23 '19 at 11:09