0

I have a JAVA RESTful webservice which will return JSON string and it was written in Java. My problem is when I send request to that webservice with below URL

http://localhost:8080/WebServiceXYZ/Users/insert

it's giving me the below error message

XMLHttpRequest cannot load http://localhost:8080/WebServiceXYZ/Users/insert/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

Here is my Code

package com.lb.jersey;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.JSONException;
import org.json.JSONObject;

@Path("/Users")
public class RegistrationService
{
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/insert")
    public String InsertCredentials (String json) throws JSONException
    {
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);

        String phone = null;
        JSONObject returnJson = new JSONObject();
        try
        {
            JSONObject obj = new JSONObject(json);
            JSONObject result1 = obj.getJSONObject("Credentials");
            phone = result1.getString("phone");
            DBConnection conn = new DBConnection();

            int checkUserID = conn.GetUserIDByPhone(phone);
            if(checkUserID <= 0)
            {
                DBConnection.InsertorUpdateUsers(phone, currentTime);
            }

            int userID = conn.GetUserIDByPhone(phone);
            int otp = (int) Math.round(Math.random()*1000);

            DBConnection.InsertorUpdateCredentials(userID, otp, currentTime);

            JSONObject createObj = new JSONObject();
            createObj.put("phone", phone);
            createObj.put("otp", otp);
            createObj.put("reqDateTime", currentTime);
            returnJson.put("Credentials", createObj);

            System.out.println(returnJson);
        }
        catch (Exception e)
        {
        }
        return returnJson.toString();
    }
}

My web.xml code

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>WebServiceXYZ</display-name>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.lb.jersey</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

I already read many articles but no progress, so please let me know, How can I handle this issue?

user3441151
  • 1,880
  • 6
  • 35
  • 79

2 Answers2

3

this is assuming you are using jetty as your server. hope it helps...

add the following code to your web.xml

<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
<init-param>
  <param-name>allowedOrigins</param-name>
  <param-value>*</param-value>
</init-param>
<init-param>
  <param-name>allowedMethods</param-name>
  <param-value>GET,POST,DELETE,PUT,HEAD</param-value>
</init-param>
<init-param>
  <param-name>allowedHeaders</param-name>
  <param-value>origin, content-type, accept</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

and the following dependency in your pom.xml

<dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlets</artifactId>
        <version>8.0.0.M0</version>
</dependency>

the link to configure tomcat is link... here is another link2 modify accordingly :)

Abhishek
  • 2,485
  • 2
  • 18
  • 25
0

You can try setting the header for the HttpServletResponse

import javax.servlet.http.HttpServletResponse;

@Path("/Users")
public class RegistrationService
{

    @Context
    private HttpServletResponse servletResponse;

    private void allowCrossDomainAccess() {
        if (servletResponse != null){
            servletResponse.setHeader("Access-Control-Allow-Origin", "*");
        }
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/insert")
    public String InsertCredentials (String json) throws JSONException
    {
        allowCrossDomainAccess();
        // your code here
    }
}
rj93
  • 523
  • 8
  • 25