Setting Content-Type and Status-Code in JSP

1.8k Views Asked by At

Its a two part question.
Part 1: I want to set the content-type of jsp page depending on the Accept header for which I'm doing

<c:if test="${fn:contains(header['accept'], 'xml')}">
    <c:set var="contentType" value="application/xml;charset=UTF-8"/>
</c:if>
<c:if test="${fn:contains(header['accept'], 'json')}">
    <c:set var="contentType" value="application/json;charset=UTF-8"/>
</c:if>
<jsp:directive.page contentType='${contentType}'/>

for which I get response like this.
I also tried
<c:set target="${pageContext.response}" property="ContentType" value="${contentType}"/>
for which I got
Invalid property in &lt;set&gt;: "ContentType"
My other EL expression are getting evaluated properly so I've already my experiment with isELIgnored attribute. I don't want to use scriptlet tags either.
Part 2: I want to set status code dynamically without the help of scriptlet tag from JSP page only.
Currently I'm doing
<% response.setStatus(200) %>
I'm aware it can be set in a servlet or a filter but I want it to be set from a jsp page or via custom tag.Kindly guide me through this.

1

There are 1 best solutions below

0
On BEST ANSWER

Solution
I stumbled upon my previous work in which I've used setAttribute() so I tried this and it worked so this is how it can be done.
For both the part create a custom tag by extending a BodyTagSupport in which we can get HttpServletResponse object this way:

HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

Once you've the response object you can easily set the Content-Type and status code