简体   繁体   English

Java Spring-从Ajax Post到Controller出现415错误

[英]Java spring - getting 415 error from ajax post to controller

I have a JSP page that makes an ajax post to a Java spring controller. 我有一个JSP页面,可以将ajax发布到Java spring控制器。 However, whenever I make the post, I am getting a 415 Unsupported Media Type error. 但是,每当发布该帖子时,都会出现415不支持的媒体类型错误。 Since I'm fairly new to Spring MVC, I'm not sure if the error is due to my response type or request type. 由于我是Spring MVC的新手,因此不确定该错误是由于响应类型还是请求类型引起的。 My ajax looks like: 我的ajax看起来像:

$.ajax({
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: "POST",
            url: "validateRedirect",
            context:document.body,
            contentType:"application/json",
            data:JSON.stringify(validateObject),
            dataType:"json"
        });

With my request mapping looking like: 与我的请求映射看起来像:

@RequestMapping(value = "/validateRedirect", method = {RequestMethod.POST}, headers="Content-Type=application/json")
public ResponseEntity<String> callToValidate(HttpServletRequest servletRequest, HttpServletResponse servletResponse, @RequestBody ValidateObj validateObject) 

Even when I try to make a post from Postman, I get the same error, so I'm thinking it's something to do with my response 即使我尝试从Postman发表帖子,也会遇到相同的错误,所以我认为这与我的回复有关

Try modifying your controller to 尝试将您的控制器修改为

@PostMapping(value = "/validateRedirect")
public ResponseEntity<ValidateObj> callToValidate(@RequestBody ValidateObj validateObject)

try it out: 试试看:

@RestController
public TestController{
    @PostMapping("/validateRedirect")
    public ResponseEntity<ValidateObj> callToValidate(@RequestBody ValidateObj validateObject){
        //...your logic
        return new ResponseEntity<ValidateObj>();
    }
}

If you are using default settings of spring, it should application/json as default accept and content type. 如果您使用spring的默认设置,则应将application/json作为默认接受和内容类型。 So you don't have to specify in annotation. 因此,您不必在批注中指定。

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

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