使用request.getParameter()还是@RequestParm哪个更好?(涉及IT技术)

3

在Spring中,哪种方式被认为是更好的软件工程实践:

1)使用Spring注释@RequestParam

@RequestMapping(value = "/doSomeThing", method = RequestMethod.GET)
@ResponseBody
public boolean doSomeThing(@RequestParam("name") String name) {
    boolean success = false;
    // do the logic
    return success;
}

2) 使用请求方法 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;
}

3
首要基于观点:第一个! - luk2302
请将此问题发布在https://codereview.stackexchange.com/上。 - arthur
一样的,我更喜欢第一个,可以跳过一些样板代码,我认为这样更易读。 - TheBakker
@arthur 目前来看,这个问题在CR上是不合适的。它被ayman转帖了并立即被投票和关闭。请不要在未检查其规则的情况下将用户重定向到其他StackExchange网站。有关CR的更多信息,请参见SO用户指南 - Zeta
2个回答

5
我会使用`@RequestParam`注释,因为这样你的代码就更易读,更容易进行单元测试。
为什么更易读?因为很明显你只是依赖于HTTP API得到单个参数。`HttpServletRequest`对象非常大,你可以做很多事情。但在这种情况下,你只使用了一个非常小的子集。当方法签名尽可能具体时,代码更易读。拥有`HttpServletRequest`类型的参数比拥有`String`更不具体。这符合接口隔离原则(客户端应该被强制依赖于它不使用的方法)。
为什么更容易测试?使用`@RequestParam`,你不需要模拟任何东西!如果你有`HttpServletRequest`作为参数,则对于单元测试,你必须小心地模拟该对象 - 小心地模拟每次调用`getParameter`。

4
另一个优点是自动转换:RequestParam可以是int、LocalDate、Long等,如果值无法转换,则会返回适当的错误响应。 - JB Nizet
@RequestParam 处理是否涉及内部调用 request.getParameter()? - Bhushan Karmarkar

1

我同意使用@RequestParam注解,我个人在我的Spring-MVC应用程序中使用它进行CRUD操作以及许多其他操作,例如在jsp页面上显示持久化表等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接