简体   繁体   English

将数据从Servlet返回到Java Client

[英]Return data from Servlet to Java Client

Hi i have a problem with returning data from Servlet to Java Client. 嗨,我有一个从Servlet返回数据到Java客户端的问题。 This is a first time that i use a servlet. 这是我第一次使用servlet。 All examples that i saw on the web return data to an HTML page but i want make a Server-Client software where Server do something and return a String List. 我在网上看到的所有示例都将数据返回到HTML页面,但我想制作服务器客户端软件,其中服务器执行某些操作并返回字符串列表。

How can i return from a GET/POST method an Array to a Client? 如何从GET / POST方法返回一个数组到客户端? What do i set in setContentType? 我在setContentType中设置了什么? I didnt understand how can i put in response the information that i want (like int , array , String) and return to the Client. 我不明白我怎么能回应我想要的信息(如int,array,String)并返回客户端。

If someone could make an example where a Java Client make a POST request and a Servlet return to him a Array or ArrayList i would be very happy. 如果有人可以举例说明Java客户端发出POST请求并且Servlet向他返回一个数组或ArrayList,我将非常高兴。

You are running into the problem of serialization . 您遇到了序列化的问题。 Serialization is where you convert some data into a format that can be transmitted. 序列化是将某些数据转换为可以传输的格式的地方。 There are several ways of doing this, some are mentioned in other answers. 有几种方法可以做到这一点,其他答案中提到了一些方法。

I would suggest using JSON as your format. 我建议使用JSON作为您的格式。 You can get a nice JSON library for java from json.org . 你可以从json.org获得一个很好的Java JSON库。 Then you can simply create a JSON array with the library and write it to the servlet's OutputStream. 然后,您可以使用库创建一个JSON数组,并将其写入servlet的OutputStream。

public void service(ServletRequest req, ServletResponse res) {
    final JSONArray arr=new JSONArray();
    for (String s : this.myListOfStrings){
        arr.put(s);
    }
    //Here we serialize the stream to a String.
    final String output = arr.toString();
    res.setContentLength(output.length());
    //And write the string to output.
    res.getOutputStream().write(output.getBytes());
    res.getOutputStream().flush();
    res.getOutputStream().close();
}

Now from your client, you can make the request and get back your ArrayList like so: 现在,从您的客户端,您可以发出请求并返回您的ArrayList,如下所示:

public ArrayList<String> contactServer(){
    final URL url = new URL(serverURL);
    final URLConnection connection=url.openConnection();
    connection.setDoOutput(true);
    /*
     * ...
     * write your POST data to the connection.
     * ...
     */
    final BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    final char[] buffer=new char[Integer.parseInt(connection.getHeaderField("Content-Length"))];
    int bytesRead=0;
    while (bytesRead < buffer.length){
        bytesRead += br.read(buffer, bytesRead, buffer.length - bytesRead + 1);
    }
    final JSONArray arr = new JSONArray(new String(buffer));
    final ArrayList<String> ret = new ArrayList<String>(arr.length());
    for (int i=0; i<arr.length(); i++) {
        ret.add(arr.get(i));
    }
    return ret;
}

You seem to need a RESTful service over http. 您似乎需要一个基于http的RESTful服务。 You should choose the way you want to serialize your objects. 您应该选择序列化对象的方式。 The typical choice is JSON - you serlialize the object to JSON and write it to the response (with Content-Type set to application/json 典型的选择是JSON - 将对象serlialize为JSON并将其写入响应( Content-Type设置为application/json

There are frameworks that do that - take a look at Spring MVC or Jersey/Resteasy 有框架可以做到这一点 - 看看Spring MVC或Jersey / Resteasy

If you want something more low-level, you can use RMI or sockets directly, without using a servlet. 如果您想要更低级别的东西,可以直接使用RMI或套接字,而无需使用servlet。 Servlets are aimed to respond to HTTP requests, which can only transmit textual data. Servlet旨在响应HTTP请求,该请求只能传输文本数据。

IMO you'll want to return data either as XML or JSON; IMO你想要以XML或JSON的形式返回数据; this makes client generation much easier. 这使客户端生成更容易。 Without knowing what your client actually is, it's difficult to be of much help, though. 但是,如果不知道客户的实际情况,很难获得很多帮助。

Sending native Objects can not easily be achieved, but JSON is a cheap alternative. 发送本机对象不容易实现,但JSON是一种廉价的替代方案。

Use a library like GSON to serialize / deserialize to / from JSON. 使用像GSON这样的库来序列化/反序列化到/从JSON。

You could just wrap the response output stream inside an ObjectOutputStream and write your Java object (which would have to be serializable) to the ObjectOutputStream . 您可以将响应输出流包装在ObjectOutputStream并将您的Java对象(必须可序列化)写入ObjectOutputStream At the client side, wrap the input stream inside an ObjectInputStream , use readObject , and cast the result to the expected object type. 在客户端,将输入流包装在ObjectInputStream ,使用readObject ,并将结果转换为预期的对象类型。

This of course makes the servlet only usable by clients written in Java, and which share the same classes as the server. 这当然使得servlet只能由用Java编写的客户端使用,并且与服务器共享相同的类。 Usually, a service offering an HTTP interface is meant to be used by any kind of client, and a more open format is chosen, like XML or JSON. 通常,提供HTTP接口的服务意味着被任何类型的客户端使用,并且选择更开放的格式,如XML或JSON。 But if that's what you need, why not using native serialization. 但如果这就是您所需要的,为什么不使用本机序列化。 That's what Spring HttpInvoker does, BTW. 这就是Spring HttpInvoker所做的,BTW。

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

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