简体   繁体   中英

Tomcat: how to get the secure port number in Java?

I'd like to embed a link to a secure page of my application in one of my unsecure pages. The secure tomcat port is configured in the server.xml file. In some deployments it's 443, 8443 etc. So what I need is a way to read the secure port from tomcat configuration to use it in the link. Is that possible?

Alternatively, simply getting access to the server.xml configuration (from within the context of the request) and parsing it myself to figure out the port number is also acceptable, but less desired.

I realize there could be several connectors, and several secure ones, so I'll leave it to my program's logic to decide which one to choose. Problem is - how do I get that info?

Thanks!

I'm pretty sure there's no API for that. You could probably keep it configurable via a servlet environ parameter in web.xml. The obvious drawback is you now have 2 places the SSL port number is configured.

Another approach is to configure security in web.xml iirc something like

 <security-constraint>
    <web-resource-collection> 
        <web-resource-name>MyLoginPage</web-resource-name>
        <url-pattern>/login</url-pattern> 
        <http-method>GET</http-method> 
        <http-method>POST</http-method> 
    </web-resource-collection> 
    <user-data-constraint> 
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
     </user-data-constraint> 
 </security-constraint>

You can just use normal links to the login page, and tomcat should automatically send redicts to the ssl connector, whichever port that is configure to.

The most simple solution is probably to search for the server.xml file in the init() method of a servlet, parse it and store the port number somewhere. The servlet should be auto-loaded.

Another option would be to put this code into your build script and copy the value into the web.xml file at build time. But that means that you must have the same Tomcat installed locally or you must have remote access to the server.xml file.

I prefer the first solution since you can have the servlet fail early and the webapp won't come up if the port can't be determined. That way, you won't have a mysterious error at some unspecified time in the future and you won't need waste time during each request (the port number can't change without a restart of Tomcat).

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