繁体   English   中英

在jsp文件中将Content-Type设置为application / json

[英]Set Content-Type to application/json in jsp file

我创建了一些jsp文件,作为响应返回一些json字符串。 但我发现Content-Type自动设置为txt

我的jsp代码看起来像

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

我怎样才能表现出类似的东西

setHeader("Content-Type", "application/json");

在这个例子中?

你可以通过Page指令来完成

例如:

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

JSP文件的MIME类型和字符编码用于它发送给客户端的响应。 您可以使用对JSP容器有效的任何MIME类型或字符集。 默认MIME类型为text / html,默认字符集为ISO-8859-1。

尝试这段代码,它也应该工作

<%
    //response.setContentType("Content-Type", "application/json"); // this will fail compilation
    response.setContentType("application/json"); //fixed
%>

@Petr Mensik&kensen john

谢谢,我无法使用页面指令,因为我必须根据某些URL参数设置不同的内容类型。 我会在这里粘贴我的代码,因为它与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 %>

提供回调时,返回:

    callback({...JSON stuff...});

内容类型为“text / javascript”

如果未提供回调,则返回:

    {...JSON stuff...}

内容类型为“application / json”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM