Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Content-Type to application/json in jsp file

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?

like image 468
Julias Avatar asked May 15 '12 07:05

Julias


3 Answers

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.

like image 157
Pau Kiat Wee Avatar answered Oct 16 '22 19:10

Pau Kiat Wee


Try this piece of code, it should work too

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>
like image 36
Petr Mensik Avatar answered Oct 16 '22 19:10

Petr Mensik


@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"

like image 3
Gael Avatar answered Oct 16 '22 19:10

Gael