[英]Why do we need the annotation “RequestParam()”
I'm learning Spring Boot right now, I don't really understand why we need this annotation.我现在正在学习 Spring Boot,我真的不明白为什么我们需要这个注释。 In my opinion, this annotation is used to rename.
在我看来,这个注解是用来重命名的。
public String home(@RequestParam("name") String othername, HttpSession session){
session.setAttribute("name", othername);
return "home.jsp"
}
So if the above code is running, I can pass my name like this: http://127.0.0.1:8080/home?name=bob
所以如果上面的代码正在运行,我可以这样传递我的名字:
http://127.0.0.1:8080/home?name=bob
But if I don't have the annotation, I can only do http://127.0.0.1:8080/home?othername=bob
, why we don't just change the name of the parameter?但是如果我没有注解,我只能做
http://127.0.0.1:8080/home?othername=bob
,为什么我们不只是改变参数的名称? I think I might misunderstand the concept of RequestParam.我想我可能误解了 RequestParam 的概念。
If you only have a handful of request parameters with default behaviour and you can easily name them as you wish, then you are right, the RequestParam
annotation is not strictly necessary.如果您只有少数具有默认行为的请求参数,并且您可以根据需要轻松命名它们,那么您是对的,
RequestParam
注释并不是绝对必要的。 However, as soon as you add PathVariables in the mix, or a request parameter eg is not required anymore, but optional, you have to add the annotation there again.但是,一旦您在混合中添加 PathVariables,或者不再需要请求参数,而是可选的,您必须再次添加注释。 Handling the parameter names is just one small aspect of that annotation.
处理参数名称只是该注释的一小部分。 Additionally, you might have to implement a legacy API, where the parameter names on the ReST API level cannot be changed, but you want to have a better name in your code for readability, clean code or other reasons.
此外,您可能必须实现旧版 API,其中 ReST API 级别上的参数名称无法更改,但您希望在代码中具有更好的名称以提高可读性、简洁的代码或其他原因。
You did not misunderstand the concept but your knowledge about it is limited.你没有误解这个概念,但你对它的了解是有限的。
@RequestParam(name = "package") String othername
.@RequestParam(name = "package") String othername
。 Renaming is just one use case of @RequestParam some of the other uses are:重命名只是@RequestParam 的一个用例,其他一些用途是:
@RequestParam(required = false)
.@RequestParam(required = false)
使参数成为可选参数。@RequestParam(defaultValue = "test")
.@RequestParam(defaultValue = "test")
添加一个默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.