开发者

How to add to HttpServletResponse in spring

I have rest controllers that returns Json response. I have added interceptor which will add some element to the response as shown below.

@Override
public void postHandle(final HttpServle开发者_JAVA百科tRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
    final long end = System.currentTimeMillis();
    final long start = (Long) request.getAttribute("_start_time");
    // how do I append to response by the difference of end - start?
    super.postHandle(request, response, handler, modelAndView);
}

If I simply add anything to the response I get the following exception:

There was an exception java.lang.IllegalStateException:getOutputStream() has already been called for this response


Adding the "end-start" time to response is not the right place. As you may actually end up breaking the JSON response you are sending back.

What you need to do is -

Option 1 - Add a response header. Something like this

httpServletResponse.addHeader("total-time", "100ms");

This way you have the data and you dont have to modifythe response. You can see the header in Firebug.

Option 2 - Add the above information in the log file so you dont have to change the servlet response.


On an HttpServletResponse, you can only use one of getWriter() or getOutputStream(), as indicated in the docs. The exception you're getting is telling you that getOutputStream() was already called, so you're not allowed to call getWriter().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜