In a JSP, how can I dynamically set the contentType?
content-type, java, jsp, servlets
Solution
You could try using scriptlets (not ideal, but I'm not sure there's another way), like this:
<%
if (actionBean.isJson()) {
response.setContentType("application/json");
} else if (actionBean.isJsonp()) {
response.setContentType("application/javascript");
}
%>
Edit: And as Joop mentions in the comments, make sure you aren't setting a contentType using a @page directive.
Problem
I have a very simple JSP that looks like this: ``` <%@ page contentType="application/json" %>${actionBean.response} ``` `actionBean.response` returns a `String`. Sometimes that string is json which has a contentType of "application/json" but sometimes that string is jsonp which has a contentType of "application/javascript". But I can't figure out how to dynamically set the value of the contentType. - I've tried using `<c:choose>` around the contentType but it gives me an error saying that I can't set the contentType twice. - I've tried using EL for the value of attribute, but it doesn't get expanded. Is there a way to dynamically set this value?