简体   繁体   English

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

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

We have a JSON Schema definition file hosted in a server and accessible via an URL. 我们有一个托管在服务器中的JSON Schema定义文件,可通过URL访问。 My Spring Controller, needs to validate the incoming JSON data (from an Ajax Call) against this schema. 我的Spring Controller需要针对此模式验证传入的JSON数据(来自Ajax调用)。

Given the URL (like.. http://myservices.json.apiOneSchema.json ) of the schema definition file, How can i read this schema definition from my Spring Controller ? 给定模式定义文件的URL(如.. http://myservices.json.apiOneSchema.json ), 如何从Spring Controller中读取此模式定义?

Spring provides Resource class using which it can be done 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();
        }

    }

The above snippet does exactly what you require. 上面的代码段完全符合您的要求。 Also once you read the Resource you can use any binding to directly convert them to your POJO. 一旦您阅读资源,您可以使用任何绑定直接将它们转换为您的POJO。 The above is just an example of how you can read it. 以上只是一个如何阅读它的例子。

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

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