Access-Control-Allow-Origin in ajax call to jersey

2019-01-18 16:06发布

问题:

I used jersey JAX-Rs as web service to query mysql.I try to consume the web-service via hybrid mobile application .

I refer this http://coenraets.org/blog/2011/11/building-restful-services-with-java-using-jax-rs-and-jersey-sample-application/#comment-440541

In server side the following code running in tomcat server7 to query sql

@Path("/employees")
 public class EmployeeResource {

EmployeeDAO dao = new EmployeeDAO();

@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Employee> findAll() {
    return dao.findAll();
}
}

public class EmployeeDAO {

public List<Employee> findAll() {
    List<Employee> list = new ArrayList<Employee>();
    Connection c = null;
String sql = "SELECT e.id, e.firstName, e.lastName, e.title FROM employee as e";

    try {
        c = ConnectionHelper.getConnection();
        Statement s = c.createStatement();
        ResultSet rs = s.executeQuery(sql);
        while (rs.next()) {
            list.add(processSummaryRow(rs));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        ConnectionHelper.close(c);
    }
    return list;
}

protected Employee processSummaryRow(ResultSet rs) throws SQLException {
        Employee employee = new Employee();
        employee.setId(rs.getInt("id"));
        employee.setFirstName(rs.getString("firstName"));
        employee.setLastName(rs.getString("lastName"));
        employee.setTitle(rs.getString("title"));
        /*employee.setPicture(rs.getString("picture"));
        employee.setReportCount(rs.getInt("reportCount"));*/
        return employee;
    }

}

I have been created the database directory with table name as employee with fields id,firstName,lastName,title.

Now i have the html file in the web-content folder of the same project .

<!DOCTYPE HTML>
<html>
    <head>
        <title>Employee Directory</title>
    </head>

    <body>

    <h1>Employee Directory</h1>

    <ul id="employeeList"></ul>

    <script src="http://code.jquery.com/jquery-1.7.min.js"></script>
    <script src="js/employeelist.js"></script>

    </body>

</html>

employeelist script

getEmployeeList();
        function getEmployeeList() {
            $.getJSON(serviceURL + 'employees', function(data) {
                $('#employeeList li').remove();
                var employees = data.employee;
                $.each(employees, function(index, employee) {
                    $('#employeeList').append(
                        '<li><a href="employeedetails.html#' + employee.id + '">'
                        + employee.firstName + ' ' + employee.lastName + ' (' 
                        + employee.title + ')</a></li>');
                });
            });
        }

This will shows the extact employee details in the Index page.

Now i have been create an html page in another project where i will put same $.getJSON call which specified above will throw error in console as

   XMLHttpRequest cannot load http://localhost:8181/jQueryJAXRS/rest/employees. Origin null is not allowed by Access-Control-Allow-Origin.

Actually I try to develop an application with client and server infrastructure .So i need to have html files in the client to consume the jersey web-services in serverside.It is really helpful if i make $.getJSON or $.ajax call from the html file in another project inorder to consume the web service.

when i use this url http://localhost:8181/jQueryJAXRS/rest/employees  in my browser

it shows xml

<employees>
<employee>
<firstName>john</firstName>
<id>1</id>
<lastName>doe</lastName>
<reportCount>0</reportCount>
<title>trainee</title>
</employee>
<employee>
<firstName>james</firstName>
<id>2</id>
<lastName>dane</lastName>
<reportCount>0</reportCount>
<title>developer</title>
</employee>
<employee>
<firstName>ramsy</firstName>
<id>4</id>
<lastName>stuart</lastName>
<reportCount>0</reportCount>
<title>QA</title>
</employee>
</employees>

but when i try through script way it will show CORS error occurs. Suggest some ideas will really help me.

Thanks in advance .

回答1:

You have to use CORS.

For that:

  1. You have to use cors-filter jar
  2. Then you have to use a filter in your web.xml :

    <filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.allowGenericHttpRequests</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowSubdomains</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, HEAD, POST, OPTIONS</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>Content-Type, X-Requested-With</param-value>
    </init-param>
    <init-param>
        <param-name>cors.exposedHeaders</param-name>
        <param-value>X-Test-1, X-Test-2</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportsCredentials</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.maxAge</param-name>
        <param-value>-1</param-value>
    </init-param>
    </filter>
    
    
    <filter-mapping>
    <filter-name>CORS</filter-name>
     <url-pattern>/EmployeeResource</url-pattern>
    </filter-mapping>
    


回答2:

Thanks Jhanvi to suggest this CORS idea. Here i explain more to have a better clarity and make it complete solution for this issue

I refer this link to solve this issue

CORS JAR

Download the CORS jar and java-property jar.Put those jars in lib folder of tomcat server.Then add the following filter as chlidnode of web-app in web.xml .

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

This solution will resolve the CORS issue .



回答3:

Thanks for this question! It lead me to a shorter way to import the jar by using maven and just adding the dependencies to the pom.xml

<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>java-property-utils</artifactId>
    <version>1.9.1</version>
</dependency>
<dependency>
    <groupId>com.thetransactioncompany</groupId>
    <artifactId>cors-filter</artifactId>
    <version>1.9.1</version>
</dependency>

Check for current versions:
http://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/1.9 http://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9



回答4:

If someone dont want to add third party libraries, they can create their own filters to add required headers in response. Please refer How to add CORS support on the server side in Java with Jersey