简体   繁体   English

Spring MVC URI针对Ajax POST请求返回404

[英]Spring MVC URI returns 404 for an ajax POST request

I am trying to make HTTP POST request to a spring controller with a json array. 我正在尝试向带有json数组的spring控制器发出HTTP POST请求。 I am getting a 404 response. 我收到404回应。 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. 我正在为项目使用Spring v3.0.5。

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

My jQuery code is given below: 我的jQuery代码如下:

$.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 呈现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 JSP页面

<!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: UPDATE日志如下:

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 UPDATE#2 Http Fox Post Request返回以下内容

data: "[{"appName":"crawler","searchQuery":"test1"},{"appName":"crawler","searchQuery":"test2"},{"appName":"crawler","searchQuery":"test3"},{"appName":"crawler","searchQuery":"test4"}]" 

When trouble shooting 404 errors I usually following steps: 解决404错误时,我通常会执行以下步骤:

  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 web.xml中的servlet映射不正确
    • 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 要查看映射,请打开调试模式以进行Spring日志记录-它会在应用程序启动时记录所有映射
    • Exception thrown by Spring during request processing and validation. Spring在请求处理和验证期间引发的异常。

    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. 为了避免碰到控制器映射问题,我使用Spring MockMVC进行控制器的单元测试-以这种方式调试问题要容易得多。

    If everything else fails, I turn on the debugger and see what exactly happens. 如果其他所有方法均失败,则打开调试器,看看会发生什么。

The data that you send in the AJAX request is an array of objects. 您在AJAX请求中发送的数据是对象数组。 But the @RequestBody maps to a String - not sure if this is correct. 但是@RequestBody映射到字符串-不知道这是否正确。

I have seen exceptions thrown in the json mapping layer wrapped as 404 errors. 我已经看到在json映射层中引发的异常被包装为404错误。 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. 找出实际异常的最佳方法是添加相关的spring源(我认为spring web和webmvc应该足够),添加一些断点并进行调试。

@RequestMapping(值=“ / something”,标头=“ Accept = application / json”,方法= RequestMethod.POST)

If spring security is used in your project, then you should add csrf token in your ajax request. 如果您的项目中使用了spring security,那么您应该在ajax请求中添加csrf令牌。 This answer contains detailed information. 该答案包含详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM