Java ajax 调用中的 Access-Control-Allow-Origin 调用 jersey rest web 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19902514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access-Control-Allow-Origin in ajax call to jersey rest web services
提问by Rajan
I used jersey JAX-Rs as web service to query mysql.I try to consume the web-service via hybrid mobile application .
我使用 jersey JAX-Rs 作为 web 服务来查询 mysql。我尝试通过混合移动应用程序使用 web 服务。
In server side the following code running in tomcat server7 to query sql
在服务器端,下面的代码在 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();
}
}
public class EmployeeDAO {
公共类 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.
我已经创建了数据库目录,表名称为员工,字段为 id、firstName、lastName、title。
Now i have the html file in the web-content folder of the 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>
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 projectwhere i will put same $.getJSON call which specified above will throw error in console as
现在我已经在另一个项目中创建了一个 html 页面,我将在其中放置相同的 $.getJSON 调用,上面指定的将在控制台中抛出错误
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.
实际上,我尝试使用客户端和服务器基础设施开发一个应用程序。所以我需要在客户端中有 html 文件来使用服务器端的 jersey web 服务。如果我从 $.getJSON 或 $.ajax 调用真的很有帮助另一个项目中的 .html 文件,以便使用 Web 服务。
when i use this url http://localhost:8181/jQueryJAXRS/rest/employees in my browser
it shows xml
它显示了 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.
但是当我尝试通过脚本方式时,它会显示发生 CORS 错误。提出一些想法真的对我有帮助。
Thanks in advance .
提前致谢 。
采纳答案by Jhanvi
You have to use CORS.
你必须使用CORS。
For that:
为了那个原因:
- You have to use cors-filter jar
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>
- 你必须使用cors-filter jar
然后你必须在你的 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>
回答by Rajan
Thanks Jhanvi to suggest this CORS idea. Here i explain more to have a better clarity and make it complete solution for this issue
感谢 Jhanvi 提出这个 CORS 的想法。在这里,我会解释更多,以便更清晰,并使其成为此问题的完整解决方案
I refer this link to solve this issue
我参考这个链接来解决这个问题
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 .
下载 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>
This solution will resolve the CORS issue .
此解决方案将解决 CORS 问题。
回答by Stefan Wasserbauer
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
谢谢这个问题!它引导我使用 maven 以更短的方式导入 jar 并将依赖项添加到 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.9http://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9
检查当前版本:
http: //mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/1.9 http://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.9
回答by Atul Kumbhar
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
如果有人不想添加第三方库,他们可以创建自己的过滤器来添加所需的响应头。请参阅如何使用 Jersey 在 Java 服务器端添加 CORS 支持