[英]How to nest @PathVariable in spring-rest?
I have a simple @RestController
service that takes query parameters, and spring automatically parses them to an bean
: 我有一个简单的
@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;
}
Query: .../rest?id=123
查询:
.../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. 理想情况下,我的查询应该是:查询:
.../rest?id=123&name=test
,“test”字符串应该进入SubParams
bean。
Is that possible? 那可能吗?
You have to register a Custom Covertor if you need to set to a inner class. 如果需要设置为内部类,则必须注册Custom Covertor。 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. 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;
}
}
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) 您可以使用@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";
}
// ...
}
maybe u should use RequestMethod.POST
, like this 也许你应该使用
RequestMethod.POST
,就像这样
@RequestMapping(value = "/rest", method = RequestMethod.POST)
public ModelAndView getGiataHotel(@ModelAttribute("subparams") SubParams subparams){
SubParams sub=subparams;
//do something...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.