0

Suppose I host a JavaEE WebApp on Payara/Glassfish (or any other WebContainer for that matter). I would reach the Servlets under the address https://a.b/appname/myservleturlpattern or as https://a.b/myservleturlpattern if the VirtualServer-Config points to the app as default.

Usually I can get that address easily inside any HttpServlet (ServletContext).

But now, when I'm running a Background task (@Schedule) in a non-servlet class, how would I get that address?

What I want: get the app's base address https://a.b/appname/ or as https://a.b/ from any class, especially from non-Servlet classes. (Cant get and don't need the myservleturlpattern because I'm not in a servlet.)

So far, my only idea is to listen to all my Servlets (extending the same custom HttpServlet anyway) and on the first call set a static variable, but thats really really unclean and hack-isch.

Any better ideas?

JayC667
  • 2,418
  • 2
  • 17
  • 31
  • What do you want from the servlet context? – Lev Kuznetsov Nov 08 '18 at 11:29
  • What I want: get the app's base address https://a.b/appname/ or as https://a.b/ from any class, especially from non-Servlet classes. (Cant get and don't need the myservleturlpattern because I'm not in a servlet.) – JayC667 Nov 08 '18 at 12:23
  • 1
    You can't get that information without a request. The container isn't aware of any of the routes a client may reach it, which is actually almost always numerous. It's available with a request because the client tells the container how it called the container. If you have to have this information I suggest you instead make an endpoint available and use a cron job to call it externally. Ideally your app should not depend on this, it makes deployments difficult. Your own solution doesn't work: what if no requests are made before the schedule? – Lev Kuznetsov Nov 08 '18 at 12:35
  • Yeah, I know that my solution is not the best. Ticket https://stackoverflow.com/questions/53206594/how-to-get-server-servlet-context-without-httpservlet-or-httpservletrequest/53206997#53206997 has exactly the same problems as I do... Thought I can guarantee that I will not be behind load balancing or proxies. – JayC667 Nov 08 '18 at 12:38
  • Proper Linkt to other topic: https://stackoverflow.com/questions/675730/finding-your-applications-url-with-only-a-servletcontext – JayC667 Nov 08 '18 at 12:51

1 Answers1

1

ServletContextListener serves exactly this purpose but there may be better solutions depending on what you want to do with with it

Lev Kuznetsov
  • 3,520
  • 5
  • 20
  • 33