我创建了一些 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 language="java" contentType="application/json; charset=UTF-8"
pageEncoding="UTF-8"%>
JSP 文件使用的 MIME 类型和字符编码 发送给客户端的响应。您可以使用任何 MIME 类型或 对 JSP 容器有效的字符集。默认 MIME 类型为text/html,默认字符集为ISO-8859-1。
尝试这段代码,它应该也能工作
<%
//response.setContentType("Content-Type", "application/json"); // this will fail compilation
response.setContentType("application/json"); //fixed
%>
@Petr Mensik 和肯森约翰
谢谢,我无法使用页面指令,因为我必须根据某些 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) {
// IMPORTANT! Sanitise the "callback",
// do not use user input directly in the response!
// This is vulnerable to XSS attacks.
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
提供回调时,返回:
callback({...JSON stuff...});
内容类型为“text/javascript”
当未提供回调时,返回:
{...JSON stuff...}
内容类型为“application/json”
[编辑]我正在回顾我的旧帖子。如果您使用此解决方案,请清理您的输入!将用户输入字符串直接放入响应中是危险的。