Controlling the HTTP response status code in XPages

June 2nd, 2011

This is a follow-up to my post on how to create custom 404 and error pages in XPages.

A very useful improvement to catching controlled errors such as "page not found" errors is to send the related HTTP status code in the response. So for "page not found" errors the HTTP response code 404 should be sent. This helps search engine crawlers understand that the page is not available whereby the search index can be updated accordingly.

The HTTP status code can be controlled with the facesContext response object by using setStatus. The following code example will generate a HTTP status code of 404 when added to the afterRenderResponse event of an error message XPage. The code example assumes that the source XPage sets the requestScope statusCode variable to "404" if the source XPage fails to find a document:

try {
	// The external context gives access to the servlet environment
	var exCon = facesContext.getExternalContext();

	// The servlet's response, check the J2EE documentation what you can do
	var response = exCon.getResponse();

	// Return HTTP status code 404 if necessary
	if (requestScope.statusCode = "404") {
		response.setStatus(404);
	}

	facesContext.responseComplete();
} catch(e) {
	_dump(e);
}

Tags: , ,

One Response to “Controlling the HTTP response status code in XPages”

  1. XSnippets: code snippets for XPages | Per Henrik Lausten Says:

    [...] I have added my first code snippet to XSnippets based on my blog entry on how to control the HTTP response status code in XPages: [...]