简体   繁体   中英

send data AJAX to @RequestBody Spring

I use response entity and request body for inserting data in spring java but I found an error. 404 not found.

my controller:

@RequestMapping(value = "insertuserlogin/", method = RequestMethod.POST)
public ResponseEntity<?> createUser(@Valid @RequestBody UserLogin user, BindingResult bindingResult,
        Validation validation, Errors error) {
    Map<?, ?> result = new HashMap<Object, Object>();
    if (bindingResult.hasErrors()) {
        String errorMessage = bindingResult.getFieldErrors().iterator().next().getDefaultMessage();
        System.out.println(errorMessage);
        return new ResponseEntity<>(errorMessage, HttpStatus.UNPROCESSABLE_ENTITY);
    } else {
        uls.saveUser(user);
        return new ResponseEntity<>(result, HttpStatus.ACCEPTED);           
    }
}

ajax:

    var data = { "description": "string", "id": 10, "username": "barubanget"}
    $.ajax({
        data: JSON.stringify(data),
        dataType: 'json',
        url : "http://localhost:8085/TaspenNCBSpring/insertuserlogin",
        type : 'POST',
        success : function(data) {
            console.log("success post!");
        },
        error : function(e) {
            console.log("error: " + e);
        }
    });     

How to fix this problem? what a format data from request body? Thanks. Bobby

I think that your @RequestMapping value is malformed. Please try to put your slash as the first character.

@RequestMapping(value = "/insertuserlogin", method = RequestMethod.POST)

Please let me know if it is useful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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