8

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.

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.

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.

5 Answers 5

7

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.

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:

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I'm going to Try
1

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

There are frameworks that do that - take a look at Spring MVC or 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.

1 Comment

i Would use RMi(that i know a bit well) but i cant becouse the free server where i would host program has only start reload stop for tomcat and anything for RMiregistry
0

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.

Comments

0

Sending native Objects can not easily be achieved, but JSON is a cheap alternative.

Use a library like GSON to serialize / deserialize to / from JSON.

2 Comments

You could just wrap the servet response output stream inside an ObjectOutputStream and write the object. That's easy enough, isn't it?
@JBNizet feel free to add it as an answer. So far, all existing answers recommend JSON.
0

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.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.