lil*_*ili 6 rest jquery jersey cross-domain
我从JavaScript客户端(在机器A上运行)到Web服务器(在机器B上运行)进行AJAX调用.客户端尝试访问由RESTful Web服务(Jersey)公开的URL,并且它被阻止并显示错误:
Access-Control-Allow-Origin不允许使用origin http:// localhost /
在服务器中,我添加了2个标头参数,允许访问任何客户端.但它没有帮助:
@Context
private HttpServletResponse servlerResponse;
@POST
@Path("testme")
public void test(){
servlerResponse.addHeader("Access-Control-Allow-Origin", "*");
servlerResponse.addHeader("Access-Control-Allow-Credentials", "true");
}
Run Code Online (Sandbox Code Playgroud)
相同的头文件适用于JSP:
<%
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Credentials", "true");
%>
<html>
<head><title>test jsp</title></head>
<body>
test
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?
谢谢
PS客户端部分是:
$.ajax({
type: "POST",
url: "http://localhost:8080/login/testme",
dataType: 'json',
success: onLoginSuccess,
error: onLoginError
});
Run Code Online (Sandbox Code Playgroud)
作为解决方案,我们实现了javax.servlet.Filter,它为每个响应添加了必需的标头:
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, java.io.IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// This should be added in response to both the preflight and the actual request
response.addHeader("Access-Control-Allow-Origin", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.addHeader("Access-Control-Allow-Credentials", "true");
}
chain.doFilter(req, resp);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17172 次 |
| 最近记录: |