Michael Gollmick, Aug 11, 2009 9:54:02 AM
Sometimes it is necessary to add some content to the HTTP header of a servers response. Some of you may have already dealt with such before and therefore have wondered how this is accomplished with XPages. For those of you, who doesn't here's a small example why one would ever like to do that:
Suppose you want to tell the client the contents language you are about to send - this is done by the Content-Language header field. A more common approach is specifying how the browsers cache should handle this particular content (that is being allowed to cache on disk or to reload the URL every single time you access it), then you would want to use the Cache-Control header field. Those of you who have dealt with the specialties of Internet Explorer 8 may want to make IE8 behave like IE7 for some reason - which is done by the X-UA-Compatible header field and can make IE8 behave pretty much like an Internet Explorer 7. If you look at your Internet Explorers address bar you have certainly seen the sometimes appearing compatibility icon that can make a Website look better in IE8. The X-UA-Compatible header is about enabling that button rather than requiring the user to click it.
But how can one add such a header field with XPages? The answer is: very easy - you need only one line of code (but you will use more for better readability/maintainability of your code).
Let's have an example. We will take the IE7 compatibility field but the example can be easily customized to be used for other fields like cache directives or the like.
At first you will need to open the Events section of your XPage (or custom control if you want to reuse the code), navigate to the beforeRenderResponse event and switch to the Script Editor code type:

Then you need to add only the following line:
facesContext.getExternalContext().getResponse().setHeader("X-UA-Compatible", "IE=EmulateIE7");
This one single line will add the X-UA-Compatible header field and will place the content IE=EmulateIE7 to it. For the purpose of making IE8 behave like an IE7 this would be already enough, but since we want to have maintainable code, we will make the code probably a bit longer:
try {
if (context.getUserAgent().isIE(8, 8)) {
var response = facesContext.getExternalContext().getResponse();
response.setHeader("X-UA-Compatible", "IE=EmulateIE7");
}
} catch (e) {
print("Something bad happened in the IE8 detection: " + e);
}
These few lines will not only handle any possibly occurring error and throw that to the servers console but will also place the header field only to responses generated to an Internet Explorer 8 browser - other browsers would ignore it anyway.