gpt4 book ai didi

java - 使用 request.getParameter() 或 @RequestParm 哪个更好?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:47 25 4
gpt4 key购买 nike

哪种方式被认为是 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;
}

最佳答案

我会使用 @RequestParam 注释,因为这样您的代码更具可读性 并且更易于单元测试

为什么更具可读性?因为很明显,您仅针对该单个参数依赖 HTTP API。 HttpServletRequest 是一个大对象,你可以用它做很多事情。在这种情况下,您仅使用该功能的很小一部分。当方法签名尽可能具体时,代码更具可读性。 HttpServletRequest 类型的参数不如 String 类型的参数具体。符合接口(interface)隔离原则(客户端应该强制依赖它不使用的方法。)

为什么更容易测试?使用 @RequestParam,您不必模拟任何东西!如果您将 HttpServletRequest 作为参数,那么对于单元测试,您必须仔细模拟该对象 - 仔细模拟 getParameter 的每次调用。

关于java - 使用 request.getParameter() 或 @RequestParm 哪个更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49844784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com