[英]Convert the request parameters in rest url to an object
Is there any direct method to convert the HTTP request parameters to an object? 是否有直接方法将HTTP请求参数转换为对象? (something like object mapper)
(类似于对象映射器)
For example, if the request http://localhot:8080/users/id=5&name=10 httpHandler() then id=5&name=10 this needs to converted to User object 例如,如果请求http:// localhot:8080 / users / id = 5&name = 10 httpHandler(),则id = 5&name = 10则需要转换为User对象
public class User {
int id;
String name;
//getters and setters
}
class MyHandler implements HttpHandler {
@Override
public void Handle(HttpExchange http) {
String param = http.get.getRequestURI().getQuery();
?? // how to map it to the User Object?
}
}
Spring does this for you automatically with RequestBody annotation. Spring使用RequestBody注释自动为您完成此操作 。
Say you make an HTTP POST request to URL http://localhost:8080/users/ with JSON request 假设您使用JSON请求向URL http:// localhost:8080 / users /发出HTTP POST请求
{
id: 1,
name: "Bob"
}
You can map this request using Spring like so: 您可以使用Spring映射此请求,如下所示:
@POST
@Path("/users")
@Consumes(MediaType.APPLICATION_JSON)
public String users(@RequestBody User user) {
// Value is "ID: 1, Name: Bob"
return "ID: " + user.getId() + ", Name: " + user.getName();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.