我想开发一个返回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文件在子目录中,我需要获取路径。
用例:
您是否知道我如何获得孔径例如
my-directory/my-sub-dir/my-json-file
或者,如果你有另一个解决方案来做同样的工作,我将非常高兴
祝你好运
答案 0 :(得分:1)
好像你不需要servlet容器来实现这一目标。如果我得到你想要做的,你想静态地提供json文件。试着调整一下: https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
答案 1 :(得分:1)
您可以通过让Spring注入HttpServletRequest
并获得如下所示来获取完整的请求网址:
@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
}