【问题标题】:Access-Control-Allow-Origin in ajax call to jersey rest web servicesajax 调用 jersey rest web 服务中的 Access-Control-Allow-Origin
【发布时间】:2013-11-23 00:40:29
【问题描述】:

我使用 jersey JAX-Rs 作为 Web 服务来查询 mysql。我尝试通过混合移动应用程序使用 Web 服务。

我参考这个 http://coenraets.org/blog/2011/11/building-restful-services-with-java-using-jax-rs-and-jersey-sample-application/#comment-440541

在服务器端运行以下代码在tomcat server7中查询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();
}
}

公共类 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;
    }

}

我已经创建了数据库目录,表名作为员工,字段 id,firstName,lastName,title。

现在我在 same project 的 web-content 文件夹中有 html 文件。

<!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>

员工名单

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>');
                });
            });
        }

这将在索引页面中显示确切的员工详细信息。

现在我已经在 另一个项目 中创建了一个 html 页面,我将在其中放置上面指定的相同 $.getJSON 调用将在控制台中引发错误,因为

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

实际上我尝试使用客户端和服务器基础架构开发应用程序。所以我需要在客户端中有 html 文件才能在服务器端使用球衣网络服务。如果我制作 $.getJSON 或 $.ajax 真的很有帮助从另一个项目中的 html 文件调用以使用 Web 服务。

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

显示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>

但是当我尝试通过脚本方式时,它会显示发生 CORS 错误。提出一些想法对我很有帮助。

提前致谢。

【问题讨论】:

    标签: java ajax json rest cors


    【解决方案1】:

    感谢 Jhanvi 提出这个 CORS 想法。在这里我解释了更多,以获得更好的清晰度,并使其成为这个问题的完整解决方案

    我参考这个链接来解决这个问题

    CORS JAR

    下载CORS jar和java-property jar。将这些jar放在tomcat服务器的lib文件夹中。然后在web.xml中添加以下过滤器作为web-app的chlidnode。

    <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>
    

    此解决方案将解决 CORS 问题。

    【讨论】:

      【解决方案2】:

      你必须使用CORS

      为此:

      1. 你必须使用cors-filter jar
      2. 然后你必须在你的 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>
        

      【讨论】:

      • 谢谢詹维。我应该在项目的构建路径中添加 jar。对吗?然后将这些 xml 添加为 web.xml 中 webapp 节点的子节点。如果我走错了路,请纠正我。
      • EmployeeDirectory Jerseycom.sun.jersey.spi.container.servlet.ServletContainercom.sun.jersey.config.property .packagesorg.coenraets1Jersey/rest/*yours 现在得到http 状态 404 ,添加 CORS jar 后
      【解决方案3】:

      感谢您提出这个问题!它引导我通过使用 maven 并只需将依赖项添加到 pom.xml 来更短地导入 jar

      <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>
      

      检查当前版本:
      http://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/1.9 http://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9

      【讨论】:

        【解决方案4】:

        如果有人不想添加第三方库,他们可以创建自己的过滤器来添加所需的标头作为响应。 请参考How to add CORS support on the server side in Java with Jersey

        【讨论】:

          猜你喜欢
          • 2015-07-17
          • 2011-07-21
          • 2016-06-10
          • 1970-01-01
          • 1970-01-01
          • 2013-08-18
          • 2013-07-17
          • 2013-03-10
          • 2013-05-08
          相关资源
          最近更新 更多