Strom
Strom

Reputation: 129

Return data from Servlet to Java Client

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.

Upvotes: 8

Views: 16416

Answers (5)

JB Nizet
JB Nizet

Reputation: 691625

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.

Upvotes: 0

Jack Edmonds
Jack Edmonds

Reputation: 33151

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;
}

Upvotes: 7

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298818

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.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160170

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.

Upvotes: 0

Bozho
Bozho

Reputation: 597016

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.

Upvotes: 1

Related Questions