Wednesday, May 20, 2009

Mind your Cache when AJAXing

When using AJAX if you use Servlets to process your request be careful that subsequent requests might look to the browser as if the previous request and hence it might not bother to make a call to the Web Service/ Servlet call again. The answer to this is to set the response header as being non-cacheable.

For Servlet call :
response.setHeader("Cache-Control","no-cache");//HTTP 1.1
response.setHeader("Pragma","no-cache");//HTTP 1.0
response.setDateHeader("Expires", 0); //prevents caching at the proxy server

For Web Service call :
<%//Forcing no cache so browser hits the AJAX urls everytime else it will cache and show old data
response.setHeader("Cache-Control", "no-store"); //HTTP 1.1

response.setHeader("Pragma", "no-cache"); //HTTP 1.0

response.setDateHeader("Expires", 0); //prevents caching at the proxy server

W3C web site has more about these tags. So next time you are AJAXing around, mind your cache!!

Redirect stack trace to log file

Log4j logging is a powerful way of debugging production issues. Here is a simple way to redirect your stack trace to log file. Typically stack trace should provide all information necessary to the developer esp. during NullPointers when e.getMessage() will not print anything more than in the output logs.

public static Log log = LogFactory.getLog(file.class);
//risky operation
} catch (Exception e) {
ByteArrayOutputStream bsos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bsos);
log.error(e.getMessage() + bsos.toString());

You can opt for a more detailed approach of logging every System.out in your application to the log file using the approach described in Nick's blog

Monday, May 04, 2009

Mastering Grails: Give your Grails applications a facelift

A great way to apply some make-up to the dirty blue look of Grails