0

When i work in spring mcv, attending requests with a controller or service, i can get the root of the my app followin this sample

@Autowired
private HttpServletRequest request;

//in method
String contextPath =  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); //maybe

But when I try to use a scheduled task, I get the null request, it does not exist in this context, since there is no a request from the browser

@Autowired
private HttpServletRequest request;

@Scheduled(cron = "10 14 12 * * *")
public void doSome() {

System.out.println("some");
 String contextPath =  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); // error HERE

There is another way, to get the root?

Community
  • 1
  • 1
jasilva
  • 730
  • 3
  • 17
  • 45
  • 1
    There is no request path because there is no request at all.. There is no logic way to get it, Why do you need it? Maybe the reason is wrong, can you share your reasons? – Aviad May 27 '14 at 20:47

2 Answers2

1

I might be wrong here, but I don't think your @Scheduled task will have access to anything from the Servlet context (e.g. HttpServletRequest) since it's started at application startup and most likely running in a thread outside of the Servlet container.

One option is to implement ServletContextAware, at which point you should have ServletContext available, then you can update your @Scheduled bean - but it doesn't look like ServletContext will provide you with all the info you need. Anyways just an idea to explore.

ikumen
  • 11,275
  • 4
  • 41
  • 41
  • Implementing `ServletContextAware` was indeed an idea worth exploring and proved fruitful for me when needing to make the `ServletContext` available to `@Scheduled` tasks. Thank you! – Brice Roncace Sep 20 '22 at 21:51
0

A @Scheduled task only runs in the background. A front end user cannot access a scheduled task in any way. If you would like to access content through your browser, you will need to create a @Controller that will be responsible for acquiring the content, whether it was acquired through a scheduled task at an earlier point in time and saved or received in "real-time."

tmanion
  • 401
  • 2
  • 11