【问题标题】:SpringBoot Path variable problem with slash带有斜线的 Spring Boot Path 变量问题
【发布时间】:2019-12-27 15:38:58
【问题描述】:

我对应该在 url 中发送的变量中的斜杠有一些问题。 例如 id 可能是这样的:

ID: /gfdge1/DkxA8P+jYw43
URL: localhost:8080/find-user//gfdge1/DkxA8P+jYw43

"error": "Internal Server Error",
    "exception": "org.springframework.security.web.firewall.RequestRejectedException",
    "message": "The request was rejected because the URL was not normalized.",

因为这个斜线放在第一位,所以问题

在此之前,我在 ID 中间遇到了这些斜线的问题,但我已经用这段代码解决了这个问题:

   @RequestMapping(name = "Get user data by ID", value = "/find-user/{userId}/**", method = RequestMethod.GET)
    @ResponseBody
    public User getUserData(@PathVariable String userId, HttpServletRequest request) {
        final String path =
                request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
        final String bestMatchingPattern =
                request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();

        String arguments = new AntPathMatcher().extractPathWithinPattern(bestMatchingPattern, path);

        String id="";
        if (null != arguments && !arguments.isEmpty()) {
            id = userId + '/' + arguments;
        } else {
            id = userId;
        }
        return userService.getUserData(id);
    }

但是当斜线放在首位时,这不适用于这种情况。 我也尝试使用 RequestParam 而不是 PathVariable,但它有一些特殊字符的问题,例如当我使用 RequestParam 时,它用空格替换“+”,...

谁能帮我解决这个问题?

【问题讨论】:

标签: java spring spring-boot path-variables


【解决方案1】:

使用字符串作为路径变量是一个固有问题,这不是您的代码的问题,而是如何解释 HTTP 请求,因此您无法在代码中执行任何操作来使其正常工作。

你确实有一些选择:

  1. 确保您使用的值不能使用“/”等特殊字符创建
  2. 完全避免在路径变量中使用字符串。

我更倾向于 2,因为为所有可能的问题字符/字符串保持 1 非常混乱且不必要。

要正确执行 2,您应该考虑让所有 REST getter 仅通过数字 ID 查找相关实体,例如

localhost:8080/find-user/3

如果您需要添加其他搜索参数,例如在您的情况下使用用户名,那么您应该使用 QueryDSL 之类的东西来创建搜索参数的谓词,这些参数作为查询参数而不是路径变量传递,例如:

localhost:8080/find-user?username=/gfdge1/DkxA8P+jYw43

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多