将数据从 Servlet 返回到 Java 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7837814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return data from Servlet to Java Client
提问by Strom
Hi i have a problem with returning data from Servlet to Java Client. This is a first time that i use a 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.
嗨,我在将数据从 Servlet 返回到 Java 客户端时遇到问题。这是我第一次使用 servlet。我在网上看到的所有示例都将数据返回到 HTML 页面,但我想制作一个服务器-客户端软件,其中服务器执行某些操作并返回一个字符串列表。
How can i return from a GET/POST method an Array to a Client? What do i set in setContentType? I didnt understand how can i put in response the information that i want (like int , array , String) and return to the Client.
如何从 GET/POST 方法将数组返回到客户端?我在 setContentType 中设置了什么?我不明白如何响应我想要的信息(如 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 向他返回一个数组或数组列表,我会很高兴。
采纳答案by Hyman Edmonds
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. You can get a nice JSON library for java from json.org. Then you can simply create a JSON array with the library and write it to the servlet's OutputStream.
我建议使用 JSON 作为您的格式。你可以从json.org获得一个很好的 Java JSON 库。然后,您可以简单地使用库创建一个 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;
}
回答by Bozho
You seem to need a RESTful service over http. 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
您似乎需要一个基于 http 的 RESTful 服务。您应该选择序列化对象的方式。典型的选择是 JSON - 您将对象序列化为 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. Servlets are aimed to respond to HTTP requests, which can only transmit textual data.
如果您想要更底层的东西,您可以直接使用 RMI 或套接字,而无需使用 servlet。Servlet 旨在响应 HTTP 请求,它只能传输文本数据。
回答by Dave Newton
IMO you'll want to return data either as XML or JSON; this makes client generation much easier. Without knowing what your client actually is, it's difficult to be of much help, though.
IMO 你想以 XML 或 JSON 形式返回数据;这使得客户端生成更加容易。但是,在不知道您的客户实际上是什么的情况下,很难提供太多帮助。
回答by Sean Patrick Floyd
回答by JB Nizet
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
. At the client side, wrap the input stream inside an ObjectInputStream
, use readObject
, and cast the result to the expected object type.
您可以将响应输出流包装ObjectOutputStream
在ObjectOutputStream
. 在客户端,将输入流包装在ObjectInputStream
、 使用 中readObject
,并将结果转换为预期的对象类型。
This of course makes the servlet only usable by clients written in Java, and which share the same classes as the server. 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. But if that's what you need, why not using native serialization. That's what Spring HttpInvoker does, BTW.
这当然使 servlet 只能由用 Java 编写的客户端使用,并且与服务器共享相同的类。通常,提供 HTTP 接口的服务旨在供任何类型的客户端使用,并且会选择更开放的格式,例如 XML 或 JSON。但如果这就是您所需要的,为什么不使用本机序列化。顺便说一句,这就是 Spring HttpInvoker 所做的。