Reputation: 567
I am new to Java RESTful webservices.
Here is my Java code:
@Path("ConversionService")
public class FeetToInchAndInchToFeetConversionService {
@GET
@Path("/InchToFeet/{i}")
@Produces(MediaType.TEXT_XML)
public String convertInchToFeet(@PathParam("i") int i) {
int inch=i;
double feet = 0;
feet =(double) inch/12;
return "<InchToFeetService>"
+ "<Inch>" + inch + "</Inch>"
+ "<Feet>" + feet + "</Feet>"
+ "</InchToFeetService>";
}
I am able to run the service and can see the output.
Here I need a help in implementing CORS in my service, can you please tell me how to write CORS in my Java code?
Do we need to write the jersy filter in separate class or is there any possibility we can directly include the "Access-Control-Allow-Origin", "*" in my Java code.
Upvotes: 0
Views: 138
Reputation: 1699
You can access the HttpServletResponse
simply by adding as a context parameter:
public String convertInchToFeet(@PathParam("i") int i, @Context HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
//...
In jQuery:
$.ajax({
crossDomain: true,
//...
Upvotes: 1