【问题标题】:How can I secure Spring controller to not accept wrong type of path variables passes in URL?如何确保 Spring 控制器不接受 URL 中传递的错误类型的路径变量?
【发布时间】:2020-01-18 06:44:30
【问题描述】:

我的 Spring 应用中有以下控制器:

@Controller
public class UserController {

    // Display single user details
    @RequestMapping(path = "/users/{id}", method = RequestMethod.GET)
    public String getUser(Model model, @PathVariable(value = "id") Integer id) {
        if(userService.getUser(id) != null) {
            model.addAttribute("user", userService.getUser(id));
            return "user_details";
        } else {
            return "redirect:/users";
        }
    }

它按我的意愿工作:如果用户存在于数据库中,则显示其详细信息。如果没有,我将被重定向到所有用户的列表。
但是,它只有在我指定整数 ID 时才能正常工作。当我提供其他类型的参数时,它会导致错误。
例如:http://localhost:8080/users/a 给出以下错误信息:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "a"

很明显,因为它需要一个整数。 我的问题是:

我应该以某种方式保护我的 Controller 方法(如果是,怎么做)以处理错误的参数类型,或者将 Integer 用于路径变量是一种不好的做法,我应该重构我的代码以使用 String 代替?最佳做法是什么?

【问题讨论】:

  • /users/{id:\\d+} 这样的东西应该可以解决问题。

标签: spring spring-mvc url controller path-variables


【解决方案1】:

您可以重构您的用户类以使用 UUID - https://docs.oracle.com/javase/8/docs/api/java/util/UUID.html

如果你正在使用休眠

@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid")
@Column(name = "uuid", unique = true)
private String uuid;

或者你可以只生成:

String uniqueID = UUID.randomUUID().toString();

【讨论】:

  • 这在我的情况下不起作用 - 我需要有数字 ID
  • 只是重构的提议。我喜欢使用 UUID 并在我能使用的任何地方使用它。
  • 需要从请求参数中解析 uuid 或者抛出一个像整数这样的异常。
【解决方案2】:

使用/users/{id:\\d+}解决

所以我的控制器现在如下所示:

@Controller
public class UserController {

    // Display single user details
    @RequestMapping(path = "/users/{id:\\d+}", method = RequestMethod.GET)
    public String getUser(Model model, @PathVariable(value = "id") Integer id) {
        if(userService.getUser(id) != null) {
            model.addAttribute("user", userService.getUser(id));
            return "user_details";
        } else {
            return "redirect:/users";
        }
    }

【讨论】:

    猜你喜欢
    • 2021-04-01
    • 2013-09-05
    • 1970-01-01
    • 2018-04-20
    • 2020-09-26
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2017-05-27
    相关资源
    最近更新 更多