简体   繁体   English

在JSP中设置内容类型和状态代码

[英]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 第1部分:我想根据我正在执行的Accept标头设置jsp页面的content-type

<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. 我的其他EL表达式得到了正确的评估,因此我已经使用isELIgnored属性进行了实验。 I don't want to use scriptlet tags either. 我也不想使用scriptlet标签。
Part 2: I want to set status code dynamically without the help of scriptlet tag from JSP page only. 第2部分:我想JSP页面中没有scriptlet标签的帮助下动态设置status code
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. 我知道可以在servletfilter中设置它,但我希望从jsp页面或通过custom标签设置它。请指导我。

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. 我偶然发现了我以前使用setAttribute()所以我尝试了一下,并且它起作用了,所以这是可以做到的。
For both the part create a custom tag by extending a BodyTagSupport in which we can get HttpServletResponse object this way: 对于这两个部分,都可以通过扩展BodyTagSupport来创建自定义标签,在该标签中,我们可以通过以下方式获取HttpServletResponse对象:

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

Once you've the response object you can easily set the Content-Type and status code 获得response对象后,您可以轻松设置Content-Typestatus code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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