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

两盒软妹~` 提交于 2019-11-26 11:59:46

问题


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?


回答1:


HttpSerlvetRequest.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 LoadBlancer 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



回答2:


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




回答3:


isSecure. Be sure to check the inherited methods.




回答4:


https and http runs on different ports. So you can get the port from the request and know from which port the request came and so that you can know the protocol. int port=request.getServerPort();



来源:https://stackoverflow.com/questions/8200853/how-can-i-know-if-the-request-to-the-servlet-was-executed-using-http-or-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!