4

ジャージー JAX-R を 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を持つemployeeとしてテーブル名を持つデータベースディレクトリを作成しました。

これで、同じプロジェクトの 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.

実際、私はクライアントとサーバーのインフラストラクチャを備えたアプリケーションを開発しようとしています。そのため、サーバーサイドでジャージ Web サービスを使用するには、クライアントに html ファイルが必要です。 Web サービスを使用するには、別のプロジェクトの html ファイルを使用します。

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 エラーが発生したことが表示されます。本当に役立つアイデアをいくつか提案してください。

前もって感謝します 。

4

4 に答える 4

12

この CORS のアイデアを提案してくれた Jhanvi に感謝します。ここで、より明確にするためにさらに説明し、この問題の完全な解決策にします

この問題を解決するには、このリンクを参照してください

コルスジャー

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 の問題を解決します。

于 2013-11-15T08:41:54.770 に答える
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

于 2014-01-19T23:06:01.013 に答える