Spring MVC中x-www-form-urlencoded请求绑定嵌套请求参数
Hey there! I’ve run into this exact issue before, so let me break down how to get your nested parameter binding working smoothly.
First, Fix the Request Parameter Format
Since you’re using x-www-form-urlencoded (not JSON), you can’t send a nested JSON structure directly. Instead, you need to represent nested properties using dot notation or bracket notation in your form parameters. Here’s what your request should look like:
Using Dot Notation (Recommended)
username=aaa&password=bbb&detail.gender=ccc&detail.location=ddd
Using Bracket Notation (Also Works)
username=aaa&password=bbb&detail[gender]=ccc&detail[location]=ddd
Spring MVC will automatically map these parameters to the nested Detail object inside your User class.
Critical Fix: Make the Detail Class Static
Looking at your User class, the inner Detail class is not marked as static—this is a common pitfall! Non-static inner classes require an instance of the outer User class to be created, which Spring can’t do automatically during parameter binding.
Update your User class to make Detail a static inner class:
@ToString @NoArgsConstructor @Data public class User { private String username; private String password; private Detail detail; // Add the static keyword here! @Data @NoArgsConstructor public static class Detail { private String gender; private String location; } }
Your Controller Method is Already Correct
You don’t need to change anything in your test method. Spring MVC will handle the binding automatically once the request format and entity class are fixed:
@RequestMapping(value = "/test") public String test(User user) { return user.toString(); }
Test It Out
You can test this with a tool like curl or Postman. Here’s an example curl command:
curl -X POST -d "username=aaa&password=bbb&detail.gender=ccc&detail.location=ddd" http://localhost:8080/test
You should get a string representation of the User object with all nested Detail properties correctly populated.
内容的提问来源于stack exchange,提问作者dailybird

