[英]How to set get query parameter name in spring @RestController Servlet?
I have a simple @RestController
and want to create a request object that holds any values from a GET
query. 我有一个简单的@RestController
并且想要创建一个包含GET
查询中任何值的请求对象。
Moreover I'd like to use variable names being different from the get query parameter names. 此外,我想使用与get查询参数名称不同的变量名称。
@RestController
public class MyServlet {
@RequestMapping(value = "/start")
public String start(@Valid MyRequest req) {
Logger.log("IN");
return req.getTest();
}
}
public class MyRequest {
@XmlElement(name = "asd")
private String test;
//getter, setter
}
Request: localhost:8080/start?asd=imhere
请求: localhost:8080/start?asd=imhere
Result: I'm seing the log statement IN
, so the servlet works. 结果:我正在查看日志语句IN
,因此servlet正常工作。 BUT req
Parameter is null. 但是req
参数为空。 Why? 为什么?
It works if I send the following url: localhost:8080/start?test=imhere
So the servlet works, but not the parameter renaming. 如果我发送以下url它是有效的: localhost:8080/start?test=imhere
所以servlet工作,但不是参数重命名。
Spring will try to build your MyRequest
object using setters or reflecting into private variables, therefore the test
variable will only be populated when you send a test
parameter. Spring将尝试使用setter构建您的MyRequest
对象或反映私有变量,因此只有在发送test
参数时才会填充test
变量。
From the documentation (@RequestMapping - Supported method argument types) : 从文档(@RequestMapping - 支持的方法参数类型) :
Command or form objects to bind request parameters to bean properties (via setters) or directly to fields... 命令或表单对象将请求参数绑定到bean属性(通过setter)或直接绑定到字段...
Edit - If you want to change names you'll likely need a Converter. 编辑 - 如果您想更改名称,您可能需要转换器。 See: 看到:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.