400 (неверный запрос) при передаче объекта json в restController - PullRequest
0 голосов
/ 12 мая 2018

Я отправляю json object using ajax на RestController, при передаче его контроллеру возникает следующая ошибка:

vendor.js: 8630 PUT http://localhost:8015/campasAdmin/master/updateState 400 (BadЗапрос)

Вот мой ajax-вызов:

$(document).on("click","#stateSave",function(event){
                 var stateId=parseInt($("#stateId").val());
                var countryId=parseInt($("#countryName").val());
                alert(countryId);  
                var stateName=$("#stateName").val();
                //parseInt($('#numberValue').val(), 10);
                var JSONObject= {  
                        "stateId":stateId,
                        "countryId":countryId,
                        "stateName":stateName
                            };

                var myJSON = JSON.stringify(JSONObject);
                //var jsonData = JSON.parse(JSONObject);
                console.log(JSONObject);    
                var url = contextPath+"/master/updateState";       
                $.ajax({        
                    url : url,           
                    type:"put",
                    date:myJSON,     
                    contentType:'application/json; charset=utf-8',  
                    async: false,       
                    success:function(response) 
                    {         

                    console.log(response.status);  
                    if(response.status)  
                        {

                         $(".editor").hide();
                         $("#countryTable tbody tr").remove();
                         $(".mainContainer").show();
                        stateList();    
                         Alert.info(response.data);
                        }
                    else{
                        Alert.warn(response.errorMessage);

                    }
                    }        
                }); 


        });

myJSON объект выглядит так:

{stateId: 1, countryId: 1, stateName: "up"}
countryId : 1
stateId   : 1
stateName :"up"

Вот мой контроллер и метод put:

@RestController
@RequestMapping(value="/master")
public class MasterController
{

    @Autowired
    private MasterServiceInter service;
    private HttpHeaders headers = null;
    Map<String, Object> message = new HashMap<String, Object>();
    //update state
        @PutMapping("/updateState")
        public ResponseEntity<Map<String, Object>> updateState(@RequestBody State theState) {
            ResponseEntity<Map<String, Object>> responseEntity=null;
            try {  
                System.out.println(theState);

            boolean res =service.updateState(theState) ;        
            if (res) {
                headers.add("head", "State");
                message.put("status", true);
                message.put("data", "State has been updated successfully  !");
                responseEntity= new ResponseEntity<Map<String, Object>>(message, headers, HttpStatus.CREATED);

            } else {
                headers.add("head", "null");
                message.put("status", false);
                message.put("errorMessage", " State has not been updated successfully  ! ");
                responseEntity=new ResponseEntity<Map<String, Object>>(message, headers, HttpStatus.NOT_FOUND);
                }
        }
            catch (Exception e) {  
                // TODO: handle exception  
                e.printStackTrace();
            }
            return responseEntity;
        }




}

Я думаю, что это проблема парсинга объекта JSON, я не могу отследить его, пожалуйста, помогите мне.

1 Ответ

0 голосов
/ 12 мая 2018

извините, все, кто там есть, набирают запотевание в моем коде ajax

$.ajax({        
                    url : url,           
                    type:"put",
                    date:myJSON,  // here is the mistake   
                    contentType:'application/json; charset=utf-8',  
                    async: false,       
                    success:function(response) 
                    {         
}
});

это должно быть

$.ajax({        
                    url : url,           
                    type:"put",
                    data:myJSON,     
                    contentType:'application/json; charset=utf-8',  
                    async: false,       
                    success:function(response) 
                    {         
                    }});

спасибо всем и стек за поток

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...