Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

spring - Passing data in the body of a DELETE request

I have two Spring MVC controller methods. Both receive the same data in the request body (in the format of an HTLM POST form: version=3&name=product1&id=2), but one method handles PUT requests and another DELETE:

@RequestMapping(value = "ajax/products/{id}", method = RequestMethod.PUT)
@ResponseBody
public MyResponse updateProduct(Product product, @PathVariable("id") int productId) {

//...
}

@RequestMapping(value = "ajax/products/{id}", method = RequestMethod.DELETE)
@ResponseBody
public MyResponse updateProduct(Product product, @PathVariable("id") int productId) {

//...
}

In the first method, all fields of the product argument are correctly initialised. In the second, only the id field is initialised. Other fields are null or 0. (id is, probably, initialised because of the id path variable).

I can see that the HttpServletRequest object contains values for all fields in the request body (version=3&name=product1&id=2). They just are not mapped to the fields of the product parameter.

How can I make the second method work?

I also tried to use the @RequestParam annotated parameters. In the method that handles PUT requests, it works. In the DELETE method, I get an exception: org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'version' is not present.

I need to pass data in the body of DELETE requests because the data contain a row version which is used for optimistic locking.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is not a Spring problem, but a Tomcat problem.

By default, Tomcat will only parse arguments that are in the form style, when the HTTP method is POST (at least for version 7.0.54 that I checked but it's probably the same for all Tomcat 7 versions).

In order to be able to handle DELETE methods as well you need to set the parseBodyMethods attribute of the Tomcat Connector. The connector configuration is done in server.xml.

Your updated connector would most likely look like:

<Connector port="8080" protocol="HTTP/1.1" 
           connectionTimeout="20000"
           redirectPort="8443"
           parseBodyMethods="POST,PUT,DELETE"
           URIEncoding="UTF-8" />

Here is documentation page for configuring Tomcat connectors.

Once you setup Tomcat to parse the parameters, Spring will work just fine (although in your case you will probably need to remove @RequestBody from the controller method)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...