Set Content-Type to application/json in jsp file

前端 未结 3 442
醉梦人生
醉梦人生 2020-12-14 06:20

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



        
3条回答
  •  难免孤独
    2020-12-14 06:44

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

提交回复
热议问题