8

We have an application running on a tomcat 7 server, and we want the http responses that send back to the client has the keep-alive header in it. Is there a way to change some configuration, like the server.xml to make this happen? Thanks a lot!

Wei
  • 131
  • 1
  • 2
  • 8

2 Answers2

7

In HTTP/1.1, connections are assumed to be keep-alive, unless otherwise specified (by "Connection: close" header). Therefore it is usually unnecessary to explicitly set keep-alive header.

Of course, you can always add a servlet filter that sets whatever headers that you need.

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
  • 2
    What I want is to send the header "Keep-Alive: timeout=120" in the Http response, such that the client knows the connection will be disconnected in 120 seconds. Is there a way to force Tomcat to send this header? – Wei Jul 25 '14 at 13:19
  • 2
    You can always do `response.setHeader("Keep-Alive", " timeout=120")` in your code. To make sure that is done for all responses, do it in a servlet filter. – ZhongYu Jul 27 '14 at 15:11
  • 2
    Yes, we can do that. But is there a way to force Tomcat send the header without the coding? The reason is that if we set the header programmatically in the filter, then we have to manually sync the code with the Tomcat setting in the server.xml. – Wei Jul 28 '14 at 14:35
  • Agreed, but how would clients know what is the Keep-Alive timeout is or when the tomcat server automatically closes its connection without informing the client? Same with max client requests using Keep-Alive, the client has no idea how many requests can be made using the persistent connection. – kisna Jul 24 '15 at 18:44
  • 2
    Most Http Clients optimize, for example, Apache HttpClient looks at this timeout and correctly recycles the Keep Alive connections. Can't believe there is no way for tomcat to support the server.xml without having to duplicate the work in your code by adding a response header. Keep-Alive: timeout=2, max=100 – kisna Jul 24 '15 at 18:50
  • @user469718 - client can have its default timeout. actually, client knows better how long connection should be cached, since it is the one that initiates requests. client can specify its connection timeout in each request. however, server usually has its own max timeout to guard against abusive client. the server does not want to keep an idle connection for too long. – ZhongYu Jul 26 '15 at 13:44
0

In Tomcat 8.5 there are some Tomcat parameters ( https://tomcat.apache.org/tomcat-8.5-doc/config/http.html ) you can set in server.xml at the Connector element:

useKeepAliveResponseHeader, keepAliveTimeout and maxKeepAliveRequests.

Attention with HTTP/2: the keep-alive header is prohibited there: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive

S. Doe
  • 685
  • 1
  • 6
  • 25