关于java:在jsp文件中将Content-Type设置为application / json

Set Content-Type to application/json in jsp file

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

我的jsp代码看起来像

1
2
3
4
5
6
7
8
9
10
11
12
<%@ 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%>

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

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

在这个例子中?


你可以通过Page指令来完成。

例如:

1
2
<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType ="mimeType [; charset = characterSet]"|
    "text / html的;字符集= 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.


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

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


@Petr Mensik&kensen john

谢谢,我无法使用页面指令,因为我必须根据某些URL参数设置不同的内容类型。 我会在这里粘贴我的代码,因为它与JSON很常见:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    <%
        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 %>

提供回调时,返回:

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

内容类型为"text / javascript"

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

1
    {...JSON stuff...}

内容类型为"application / json"