简体   繁体   中英

Is it possible to return more than one value from a servlet to client?

I have a servlet which generates a .png image and writes it into the OutputStream as a byte array.

I'd like to create an application which fires that servlet and downloads the generated image. I also would like to measure how much time does it take for the servlet to generate the image not including the time of parameter checking and such things. I know it's impossible from a client side application so the servlet itself should measure this time then send the measured value back to the client side app.

My problem : how is it possible to send more than one thing from a servlet: the image and the time value as well?

Shall I use for example JSON? Or if I write the image (as a byte array) and the time value (as a long value) into the OutputStream how can I read it out on client side?

In that case, you can send a header parameter.

long startTime = System.currentTimeMillis();

// Generate the image

long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
response.setHeader("ElapsedTime", elapsedTime);

It depends on your client. As you mentioned servlet deals with bytes. It can write to output stream what you want using protocol that you choose. For example write int value that contains processing time in milliseconds followed by the byte array that contains your image.

But what kind of client will read this stream? If it is programatic thick client you can implement similar logic there. But I believe it is expected to be a web browser that creates HTTP request because it is rendering HTML with <img> tag. But browser does not know to get additional data.

If however your you are using AJAX to get your image you can put additional data into HTTP response header and then read its value at client side.

Yes we can return more than one value to client from HttpServletResponse.

From the servlet version 2.2 Servlets have also been given the ability to send multiple values for the same response header using methods in HttpServletResponse.

The new addHeader(String name, String value) method sets the header to the given value. While the traditional setHeader() method would replace any existing value or values, addHeader() leaves current settings alone and just sets an additional value. There's also addIntHeader(String name, int value) and addDateHeader(String name, long date).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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