我有一个简单的@RestController
服务,它接受查询参数,而spring会自动将它们解析为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;
}
查询:.../rest?id=123
现在我想用嵌套类构造参数对象。我怎样才能做到这一点?
public class SubParams {
private String name;
//some more
}
理想情况下,我的查询应该是:查询:.../rest?id=123&name=test
,以及"测试" string应该进入SubParams
bean。
这可能吗?
答案 0 :(得分:1)
如果需要设置为内部类,则必须注册Custom Covertor。改变如下:
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/rest", method = RequestMethod.GET)
public MyDTO getGiataHotel(@ModelAttribute("subParam") MyParams params, @Valid MyParams p) {
//Do stuff
}
subParam 表示已注册转换的转换器。
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;
}
}
答案 1 :(得分:0)
您可以使用@ModelAttribute注释来实现此目的:http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args(这不是在Path参数中,而是在requestParams中获取/发布)
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petForm";
}
// ...
}
答案 2 :(得分:0)
也许你应该使用RequestMethod.POST
,就像这样
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public ModelAndView getGiataHotel(@ModelAttribute("subparams") SubParams subparams){
SubParams sub=subparams;
//do something...
}