Reputation: 49
Which way is considered as better Software Engineering practice in spring:
1) using the spring annotation @RequestParam
@RequestMapping(value = "/doSomeThing", method = RequestMethod.GET)
@ResponseBody
public boolean doSomeThing(@RequestParam("name") String name) {
boolean success = false;
// do the logic
return success;
}
2) using the request method getParameter
@RequestMapping(value = "/doSomeThing2", method = RequestMethod.GET)
@ResponseBody
public boolean doSomeThing2(HttpServletRequest request) {
boolean success = false;
String name = request.getParameter("name");
// do the logic
return success;
}
Upvotes: 3
Views: 935
Reputation: 13235
I would use @RequestParam
annotation because that way your code is more readable and easier to unit-test.
Why more readable?
Because it is clear that you depend on HTTP API only for that single parameter. HttpServletRequest
is big object, you could do many things with it. An in this case you are using only very small subset of that functionality. Code is more readable when method signature is as specific as possible. Having parameter of type HttpServletRequest
is less specific that parameter of type String
.
It is in line with Interface segregation principle (client should be forced to depend on methods it does not use.)
Why easier to test?
Using @RequestParam
, you do not have to mock anything!
If you have HttpServletRequest
as parameter then for unit test you have to carefully mock that object -carefuly mocking every invocation of getParameter.
Upvotes: 5
Reputation: 59
Yep i agree with the @RequestParam annotation i personally used in my spring-mvc application for CRUD operations and and many other operations like to display persisted table on the jsp page and all..
Upvotes: 1