How would i go about checking if a person is refreshing a jsp page? Could we make it for example that every time we reload a page we would first check if this happens and then we check with System.out.print().
2 Answers
Hmm, first System.out.print
is of little use in a JSP because it will never reach the client. At best it will end in the logs, at worst it is lost.
Then in simple cases you can trust the HTTP Referer
header that is supposed to give the previous page url. But it is an unreliable way because it may not be transmitted by the browser. A more reliable way is to use a session variable to store the current page (you could use a filter to set it after a request is being processed). If the requested page is the current page, then it is being refreshed.
In complex use cases (AJAX requests) you should first define what is a page, because not every request will constitute a page: some will call a page while some only ask data. But once this is clear, you can apply the previous way: if the user asks for a page which is the current page (as stored in session), then the page is being reloaded.

- 143,923
- 11
- 122
- 252
If you want to do something every time a page load. Then you can use simple javascript for that. Try this
window.onload=function()
{
dosomething();
console.log("Page is loaded");
}
You can learn about it from here. https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

- 349
- 1
- 8
-
I think the OP wants to do this *server-side* if the page is *reloading*, not client-side every time the page is loading. – dan1st Feb 10 '20 at 05:46
-
He has not specified anything regarding that. If it is server-side then just check every time the controller or servlet is called in the back-end. – Silverfang Feb 10 '20 at 06:04
-
He has specified it. He said he wants to do it with `System.out.println()`. – dan1st Feb 10 '20 at 06:05
-
-
If it is jsp `System.out.println()` can be written both at your server side and in your jsp too. Furthermore onload function works everytime the page loads. When refreshing any page we are loading the page again. You can use unload with it to make it work – Silverfang Feb 10 '20 at 06:13
-
Yes `System.out.println()` can be written on the server-side but it **cannot** be called by javascript. – dan1st Feb 10 '20 at 06:32
-
I never said you can call that from java script. I said it can be written in jsp inside <% %> tag. So it will show up in console whenever the page is accessed. – Silverfang Feb 10 '20 at 06:37