【问题标题】:Passing a list of strings in a Spring MVC controller using Jquery Ajax使用 Jquery Ajax 在 Spring MVC 控制器中传递字符串列表
【发布时间】:2020-03-11 17:08:42
【问题描述】:

我正在尝试使用 JQuery Ajax 将字符串列表传递给 MVC 控制器,但我收到错误 No mapping for POST /myUrl/myContext/p

这是我的 jquery 函数:

$('#myButton').on('click', function(){
    var strings = [];
    $('#myForm input[type=checkbox]:checked').each(function(){
        var string = $(this).closest('tr').find('#mySpan').text();
        strings.push(string);
    });

    $.ajax({
        url : 'myContext/p',
        dataType : 'json',
        type: 'POST',
        data : {strings : strings},
        success: function(response) {
            //my success function           
            }
        },
        error: function(e) {
            //my error function
            }   
        }
    });

})

这是我的控制器:

@PostMapping(value="/myContext/p")
    public ResponseEntity<MyResponse> doPost(
            @RequestParam(value="strings" ,required=true) List<String> strings)
                    throws Exception{
        MyResponse response = new MyResponse();

        //my Code

        response.setData(strings);
        return new ResponseEntity<MyResponse>(response, HttpStatus.OK);
    }

【问题讨论】:

    标签: javascript java jquery ajax spring-mvc


    【解决方案1】:

    我解决了这个问题:

    @PostMapping(value="/myContext/p", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
                produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
        public ResponseEntity<MyResponse> doPost( ArrayList<String> strings) throws Exception{
            MyResponse response = new MyResponse();
    
            //code
    
            response.setData(strings);
            return new ResponseEntity<RestResponse>(response, HttpStatus.OK);
        }
    

    【讨论】:

      【解决方案2】:

      我通常会使用@RequestBody 而不是@RequestParam 作为字符串参数。

      【讨论】:

      • 另外,请检查映射中的网址。您的 javascript 具有没有前导斜杠的“myContext/p”,并且控制器具有前导斜杠。在我的 js 中,我通常在我的 url 前面加上 jsp 中的 ${pageContext.request.contextPath}。
      猜你喜欢
      • 2016-07-18
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-10-25
      • 2017-10-23
      • 1970-01-01
      • 2021-08-02
      • 2016-02-26
      相关资源
      最近更新 更多