繁体   English   中英

如何使用Spring Controller从URL读取文件?

[英]How to read a file from URL using Spring Controller?

我们有一个托管在服务器中的JSON Schema定义文件,可通过URL访问。 我的Spring Controller需要针对此模式验证传入的JSON数据(来自Ajax调用)。

给定模式定义文件的URL(如.. http://myservices.json.apiOneSchema.json ), 如何从Spring Controller中读取此模式定义?

Spring提供了可以使用它的Resource

 public static void main( String[] args )
    {
        ApplicationContext appContext = 
           new ClassPathXmlApplicationContext(new String[] {"If-you-have-any.xml"});

        Resource resource = 
           appContext.getResource("http://www.common/testing.txt");

    try{
          InputStream is = resource.getInputStream();
          BufferedReader br = new BufferedReader(new InputStreamReader(is));

          String line;
          while ((line = br.readLine()) != null) {
             System.out.println(line);
          } 
          br.close();

        }catch(IOException e){
            e.printStackTrace();
        }

    }

上面的代码段完全符合您的要求。 一旦您阅读资源,您可以使用任何绑定直接将它们转换为您的POJO。 以上只是一个如何阅读它的例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM