the singularity of being and nothingness
CFScript Alternative to CFHeader
In another post, I wrote about how you can replicate the functionality of cfcontent’s “reset” attribute in CFScript. The other day, I came across a related issue of needing to be able to do the same thing (all code in CFScript, that is) for cfheader. Fortunately, by using the same approaching of tapping into the underlying Java methods, this is extremely easy.
Setting Status
To set the status code for the page request, simply do the following:
pc = getpagecontext().getresponse(); pc.getresponse().setstatus(301);
No big deal there. Also, be aware that the setstatus() method can take an optional second string attribute, so if you wish to define a message to accompanying the status code, feel free 🙂
Setting Headers
Honestly, I use headers in CF mostly for downloading files, or returning certain content types. Just as with setting the status, it’s pretty freaking simply to do in CFScript:
pc = getpagecontext().getresponse(); pc.getresponse().setcontenttype('application/vnd-ms.excel'); pc.setHeader("Content-Disposition","inline;filename=MyFile.xls");
Print article | This entry was posted by existdissolve on October 30, 2010 at 1:57 pm, and is filed under ColdFusion. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 13 years ago
This is a wonderful snippet, for sure! The one thing I needed to add to the mix was the javacast() function to make addHeader work with page variables.
res=pc = getpagecontext().getresponse();
res.addHeader(javacast(“string”,headerName),javacast(“string”,api.headers[ headerName ]));
Thought I might share for others who stumble upon this tip via google. Thanks for pointing out the Java direction for this.
about 13 years ago
Very cool!
I shortened setting a header to:
getPageContext().getResponse().setstatus(500);
Thanks 🙂
about 12 years ago
Thanks for sharing. Exactly what I needed.
about 12 years ago
Thank you as well, this worked perfectly!
about 11 years ago
This is what worked for me in CF9
header statuscode=”404″ statustext=”Not Found”;
about 11 years ago
tried this:
> header statuscode=”404″ statustext=”Not Found”;
Generates the error “function keyword is missing in FUNCTION declaration. The CFML compiler was processing: A script statement beginning with header on line 2, column 1”
I am running CF 9.01 with all patches. On the other hand
> getPageContext().getResponse().setstatus(500);
Worked magnificently on a single line. Thanks to all concerned!
about 9 years ago
how to add filepath in content