ufk
ufk

Reputation: 32094

How can I know if the request to the servlet was executed using HTTP or HTTPS?

I wrote a servlet in Java and I would like to know if the request to that servlet was executed using HTTP or HTTPS.

I thought I can use request.getProtocol() but it returns HTTP/1.1 on both methods.

Any ideas?

Upvotes: 75

Views: 57836

Answers (3)

Ramesh PVK
Ramesh PVK

Reputation: 15446

HttpServletRequest.isSecure() is the answer. The ServletContainer is responsible for returning true in the following cases:

  • If the ServletContainer can itself accept requests on https.
  • If there is a LoadBalancer in front of ServletContainer and the Load Balancer has got the request on https and has dispatched the same to the ServletContainer on plain http. In this case, the LoadBalancer sends X-SSL-Secure : true header to the ServletContainer, which should be honored.

The Container should also make this request attributes available when the request is received on https:

  • javax.servlet.http.sslsessionid
  • javax.servlet.request.key_size
  • javax.servlet.request.X509Certificate

Upvotes: 105

Cratylus
Cratylus

Reputation: 54074

You can't reliably depend on port numbers.
But you can depend on the scheme:

Use: request.getScheme() to see if it is https.

If it is then it is secure connection.

I believe this should work regardless of Tomcat version

Upvotes: 29

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

isSecure. Be sure to check the inherited methods.

Upvotes: 11

Related Questions