Set Content-Type to application/json in jsp file

Julias picture Julias · May 15, 2012 · Viewed 116.2k times · Source

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?

Answer

Pau Kiat Wee picture Pau Kiat Wee · May 15, 2012

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.