I have a Grails 2.3.6 app running as a WAR file in a server. Currently it's running in Tomcat 7.
In future we might have the app run in other servers too.
Now the problem i face is unique. In one of the service groovy files i need to get the port number for the running app.
For Tomcat the port number is set in server.xml and one potential way to get that will be to read from there.
But am looking for a more generic solution. So that even if the WAR file is deployed in other type of servers, i could get the port number.
Any suggestions are welcome!
The port (singular) isn't necessarily well-defined, eg you can have a Tomcat configured with several connectors listening on different ports, or serving both http and https. In the context of a particular request you can talk about "the port" that that request was received on, but then what happens if your app is behind a reverse proxy or load balancer...
The only reliable approach is to manually specify the appropriate port number/URL/whatever in a configuration file (eg a grails.config.locations
external).
You'll probably need to set the grails.serverURL
configuration property to the base root of the application. In the development
environment, this is typically something like
grails.serverURL = "https://localhost:8080/example"
and in the production
environment
grails.serverURL = "https://example.org"
If you don't set this correctly, certain things won't work, eg generating absolute URLs. If this property is set correctly, then getting the port in a service is as simple as:
class MyService {
def grailsApplication
Integer getPort() {
String basePath = grailsApplication.config.grails.serverURL
// parse out the path (exercise for reader)
}
}
If you need the port in the service you can get it from HttpServletRequest as follows:
HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.currentRequestAttributes()).getRequest()
def port = request.getServerPort()
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.