Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

java - Why do we need the annotation "RequestParam()"

I'm learning Spring Boot right now, I don't really understand why we need this annotation. 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

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? I think I might misunderstand the concept of RequestParam.

question from:https://stackoverflow.com/questions/65858734/why-do-we-need-the-annotation-requestparam

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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. However, as soon as you add PathVariables in the mix, or a request parameter e.g. is not required anymore, but optional, you have to add the annotation there again. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...