【问题标题】:Get all path variable获取所有路径变量
【发布时间】:2017-09-22 16:53:50
【问题描述】:

我想开发一个返回 json 文件的服务。

@RequestMapping(value = "/{fileName}/**", method = RequestMethod.GET, produces = { "application/json" })
public String jsonREST(@PathVariable String fileName) {
    StringBuilder jsonBuilder = new StringBuilder();
    logger.info("===> File name: " + fileName);
    try {
        BufferedReader bf = new BufferedReader(new FileReader("fileName + ".json"));
        String line = null;
        while ((line = bf.readLine()) != null) {
            jsonBuilder.append(line);
        }
    } catch (Exception e) {
        System.out.println("Error Parsing: - ");
    }
    return jsonBuilder.toString();
}

例如,如果 json 文件位于子目录中,我需要获取路径。

用例:

  • localhost:8080/my-directory/my-sub-dir/my-json-file
  • localhost:8080/my-json-file

您是否知道我如何获得例如孔路径

my-directory/my-sub-dir/my-json-file

或者,如果您有其他解决方案来做同样的工作,我会很高兴的

最好的问候

【问题讨论】:

  • 您的代码由于各种原因效率低下。为什么不直接返回 FileSystemResource 并让 Spring Boot 自己完成这一切?
  • 谢谢@lyubomyr,但你知道我该怎么做吗?我的意思是如何获得路径

标签: java json spring rest spring-boot


【解决方案1】:

您可以通过让 Spring 注入 HttpServletRequest 并按如下方式获取完整的请求 url:

@RequestMapping(value = "/{fileName}/**", method = RequestMethod.GET, produces = { "application/json" })
public String jsonREST(HttpServletRequest request, @PathVariable String fileName) {
    String uri = request.getRequestURI();

    //Do your stuff here
}

【讨论】:

    【解决方案2】:

    似乎您不需要 servlet 容器来实现这一点。如果我得到你想要做的事情,你想静态地提供 json 文件。尝试调整这个: https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot

    【讨论】:

      猜你喜欢
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-04-14
      相关资源
      最近更新 更多