2

My websites are caching the REST requests. I am happy with the speed of the websites and would like to retain the cache. However, I have discovered that the same file is returned after I have made a POST/PUT/DELETE request. This means that the updated database isn't called. The same happens after refreshing the page. I would like to have updated information from the database after a POST/PUT/DELETE request.

I am just wondering if I can maybe set a conditional statement to cache the files if the last REST request isn't POST/PUT/DELETE? The website is hosted on a shared web hosting platform and I can amend the .htaccess file. Greatly appreciated for any ideas. I hope my explanation is clear but please feel free to reach out if it's not. Thank you in advance

Yandy
  • 95
  • 6
  • what are the UI scripts you are using ? I am posting one answer considering javascript as scripting language. – Shuvajit Ghosh Dec 30 '21 at 06:23
  • Hi Shuvajit Ghosh,I'm using Angular. I'm wanting browser cache for most of the time except if there's an update on the database. The answer you've posted seems to be stopping browser caching as a whole, is that right? – Yandy Dec 30 '21 at 07:26
  • yes just use a flag to check (like I have used "last-request") inside the doGet(req, resp ) or doPost(rq,rs) or put() delete() methods wherever you want to stop the browser caching. Please vote or accept the answer else you can ask questions or comment if the answer not working with sample errors/logs you are getting from your application. I will not suggest you to handle this in UI controller level. Instead you should handle it on java layer. – Shuvajit Ghosh Dec 30 '21 at 07:41

1 Answers1

0

To stop browser caching we can add the below properties in an HTML as meta headers.
Cache-Control: no-cache, no-store, must-revalidate Pragma: no-cache Expires: 0

We have to save the above headers in the html page which will be among the parent HTMLs to be used.

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

The below code can be used from java servlet or nodejs

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0");

servlet code sample as follows

public void doGet(HttpServletRequest req,HttpServletResponse response) throws ServletException,IOException  
{   
    if(req.get[some field name].equals("last_request")){
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setHeader("Expires", "0");
    }

} 

Below link can be a reference of this thread

How do we control web page caching, across all browsers?

Shuvajit Ghosh
  • 108
  • 2
  • 17