简体   繁体   中英

Setting Content-Type and Status-Code in JSP

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 这个。
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM