0

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.

1 Answer 1

1

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,
    //...
Sign up to request clarification or add additional context in comments.

1 Comment

after adding the header also it is not working, im getting same cross origin domain error. im calling the service from javascript, do we need to add the same in java script also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.