I am implementing Cross Resource Origin Sharing in Java Web services using Jersey.I created resource as followes:
@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();
}
and making post request using javascript as :
<!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>
When i clicked getSubjects Button in chrome I am getting error as : XMLHttpRequest cannot load ..localhost:8888/WebservicesServer/restful/getserver/getSubjects. Origin null is not allowed by Access-Control-Allow-Origin. But i am able to get response with GET request,problem is with POST request my browser url file:///E:/Documents%20and%20Settings/Srinivas/Desktop/wars/JSClient2.html (File system) I tried in many ways like by setting origin etc, still unable to get json response (Server is Tomcat 7) please help to overcome this problem.
If you are using CORS then you should implement it as a filter rather than attempt to embed it in every method of every resource. Here's a simple example (you might want to tweak the settings to restrict it if that's of concern to you):