我正在使用 Jersey 在 Java Web 服务中实现跨资源源共享。我创建的资源如下:
@POST
@Path("/getSubjects")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getSubjects(TokenCheck tc) throws IOException, ServletException{
String token = tc.getToken();
String result = "";
if(!token.equals("") && !token.equals(null)){
context.getRequestDispatcher("/GetSubjectsWs?token="+token).include(request, response);
String subs = request.getAttribute("subjects").toString();
result = "{\"subjects\":\""+subs+"\"}";
}else {
result = "{\"subjects\":\"['Invalid Token login again']\"}";
}
JSONObject j = null;
try {
j = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
return Response.status(200).entity(j).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST, GET, OPTIONS").header("Access-Control-Allow-Headers", "Content-Type:application/json").build();
}
并使用 javascript 作为发布请求:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Client</title>
<script type="text/javascript">
function restReq() {
var url = "http://localhost:8888/WebservicesServer/restful/getserver/getSubjects";
var json = {
"token":"8495C211F11C9B18E6651E03EB2995BC"
};
var client = new XMLHttpRequest();
client.open("POST", url, true);
client.setRequestHeader("Access-Control-Request-Methods", "POST");
client.setRequestHeader("Content-Type", "application/json");
client.send(json);
client.onreadystatechange = function() {
if (client.readyState == 4) {
if ( client.status == 200)
console.log("success: " + client.responseText);
else
console.log("error: " +client.status+" "+ client.responseText);
}
};
}
</script>
</head>
<body>
<input type="button" value="getSubjects" onclick="restReq();">
</body>
</html>
当我单击 chrome 中的 getSubjects 按钮时,我收到错误消息:XMLHttpRequest cannot load ..localhost:8888/WebservicesServer/restful/getserver/getSubjects。Access-Control-Allow-Origin 不允许 Origin null。但是我能够通过 GET 请求得到响应,问题是 POST 请求我的浏览器 url file:///E:/Documents%20and%20Settings/Srinivas/Desktop/wars/JSClient2.html(文件系统)我尝试了很多通过设置原点等方式,仍然无法获得 json 响应(服务器是 Tomcat 7)请帮助克服这个问题。