Reputation: 86627
I have a simple @RestController
service that takes query parameters, and spring automatically parses them to an bean
:
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/rest", method = RequestMethod.GET)
public MyDTO getGiataHotel(@Valid MyParams p) {
Sysout(p.getId()); //prints "123"
}
public class MyParams {
private int id;
//private SubParams subs;
}
Query: .../rest?id=123
Now I'd like to structure the parameter object with nested classes. How can I achieve this?
public class SubParams {
private String name;
//some more
}
Ideally my query should be: Query: .../rest?id=123&name=test
, and the "test" string should go into the SubParams
bean.
Is that possible?
Upvotes: 3
Views: 943
Reputation: 186
maybe u should use RequestMethod.POST
, like this
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public ModelAndView getGiataHotel(@ModelAttribute("subparams") SubParams subparams){
SubParams sub=subparams;
//do something...
}
Upvotes: 0
Reputation: 5786
You have to register a Custom Covertor if you need to set to a inner class. The change would be following:
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/rest", method = RequestMethod.GET)
public MyDTO getGiataHotel(@ModelAttribute("subParam") MyParams params, @Valid MyParams p) {
//Do stuff
}
The subParam denotes that there is a converter registered for conversion.
public class MyParamsConverter implements Converter<String, MyParams> {
@Override
public MyParams convert(String name) {
MyParams myParams = new MyParams();
SubParams subParams = new SubParams();
subParams.setName(name);
myParams.setSubParams(subParams);
return myParams;
}
}
Upvotes: 1
Reputation: 1561
You can achieve this by using the @ModelAttribute annotation : http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args (this is not in the Path parameters, but in the requestParams either get/post)
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petForm";
}
// ...
}
Upvotes: 0