I am created some jsp file that returns as a response some json string. But I see that the Content-Type is set to txt automatically
My jsp code looks like
<%@ page import="java.util.Random" %>
<%@ page language="java" %>
<%@ page session="false" %>
<%
String retVal = "// some json string";
int millis = new Random().nextInt(1000);
// System.out.println("sleeping for " + millis + " millis");
Thread.sleep(millis);
%>
<%=retVal%>
How can I perform something like
setHeader("Content-Type", "application/json");
in this example?
This question is related to
java
http
jsp
http-headers
content-type
Try this piece of code, it should work too
<%
//response.setContentType("Content-Type", "application/json"); // this will fail compilation
response.setContentType("application/json"); //fixed
%>
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
Source: Stackoverflow.com