spring休息通过ajax打电话

时间:2017-05-25 09:27:18

标签: ajax spring rest spring-mvc model-view-controller

当我通过 ajax 向Spring Rest发送 POST 请求时,我遇到了问题我遇到了以下错误。但它与Postman工具一起工作正常。

如何解决这个问题?请帮忙。

enter image description here

@RestController
public class LoginController {

    @Autowired
    LoginServiceBo loginServiceBo;

    public void setLoginServiceBo(LoginServiceBo loginServiceBo) {
        this.loginServiceBo = loginServiceBo;
    }

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public ModelAndView redirectLoginForm() {
        System.out.println("Login Page...");
        return new ModelAndView("login");
    }

    @RequestMapping(value="/login",method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Login> login(@RequestBody Login login) {
        System.out.println("Checking Login Credentials...");
        boolean isValid=loginServiceBo.checkUserLogin(login);

        if(isValid) {
            System.out.println("Found...");
            return new ResponseEntity<Login>(login, HttpStatus.ACCEPTED);
        }
        System.out.println("Not Found...");
        return new ResponseEntity<>(login, HttpStatus.NOT_FOUND);   
    }

}

在javascript中

function RestPost() {
userId = document.getElementById("userId");
password = document.getElementById("password");
var json = {
    "userId": userId,
    "password": password
};

$.ajax({
    url: prefix + "/login",
    type: 'POST',
    data: JSON.stringify(json),
    cache: false,
    dataType: 'json',
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json");
    },
    success: function(response) {
        alert(JSON.stringify(response));


    },
    error: function(jqXhr, textStatus, errorThrown) {
        alert(jqXhr.status + ' ' + jqXhr.responseText);


    }
});
}

0 个答案:

没有答案