简体   繁体   中英

How to use the @RequestBody annotation in Spring MVC inheritance

First, look at the following code

public interface DemoInterface {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    String test(@RequestParam String message);

}

Then I let a class implement this interface with annotations

@Controller
public class DemoClass implements DemoInterface{
    @Override
    public String test(String message) {
        /** TODO something useing the message **/
    }
}

This is no problem, I can access my test method via http://ip:port/test?message=something .

But when I need to pass a class instead of a string:

public interface DemoInterface {
    @RequestMapping(value = "/test", method = RequestMethod.POST,  consumes = "application/json")
    String test(@RequestBody User user);
}

public class User{
    private String name;
    /** some other fileds、 geters and seters **/
}

@Controller
publci class DemoClass implements DemoInterface{
    @Override
    public String test(User user) {
        /** TODO something useing the user's fileds **/
    }
}

At this time, although I can access http://ip:port/test , when I set the request body to json in the Google Chrome browser's Restlet Client, I can't get the user value in the test method, the name always empty. My json is like this:

{"name":"Vincent Kang"}

Is this because I can't get annotations for formal parameters in the methods I inherit? Because I found that even in the latter case, using http://ip:port/test?name=Kanghouchao , I can still get the name in the test method, RequestBody seems to be invalid.

May be I should add @RequestBody in my subclass's field

@Controller
publci class DemoClass implements DemoInterface{
    @Override
    public String test(@RequestBody User user) {
        /** TODO something useing the user's fileds **/
    }
} 

It's OK now

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