Jquery调用Java RESTful服务不工作CORS [英] Jquery call of Java RESTful service not working CORS
问题描述
我有一个休息服务部署在Tomcat 7并运行。我可以通过浏览器获取响应数据,但是当我通过jQuery尝试它显示一个错误。请检查快照。
@Override
public void doFilter(ServletRequest req,ServletResponse res,
FilterChain链接)throws IOException,ServletException {
HttpServletRequest httpReq =(HttpServletRequest)req;
HttpServletResponse httpRes =(HttpServletResponse)res;
//System.out.println(\"Client Ip is:+ SecurityFilter.getClientIpAddr(httpReq));
String domain = new URL(httpReq.getRequestURL()。toString())。getHost();
//System.out.println(\"Domain is+ domain);
// referrer
String referrer = httpReq.getHeader(referer);
//System.out.println(\"Referral URL is - + referrer);
//安全密钥
String securityKey = httpReq.getParameter(secKey);
//System.out.println(\"Security Key Parameter+ securityKey);
//原始
//没有起始标头存在意味着这不是一个跨域请求
String clientOrigin = httpReq.getHeader(Origin);
//System.out.println(\"Origin of the request+ clientOrigin);
// CORS实现
httpRes.addHeader(Access-Control-Allow-Origin,*);
httpRes.addHeader(Access-Control-Allow-Methods,GET,POST,OPTIONS);
// httpRes.addHeader(Access-Control-Allow-Origin,clientOrigin);
if(OPTIONS.equalsIgnoreCase(httpReq.getMethod())){
httpRes.addHeader(Access-Control-Allow-Credentials,true);
}
ValidateClient vl = new ValidateClient();
String secKey =fmg_seckey; //SEC_1;;
String clientUrl =fmggroup.com; //www.xyzclient1.com;
//如果请求来自第三方。如果所有
//请求来自同一服务器,则引用将为null。
if(referrer!= null){
clientUrl = referrer.split(/)[2];
secKey = securityKey;
}
//System.out.println(\"Security Key+ secKey);
//System.out.println(客户端的域名+ clientUrl);
if(vl.isValidClient(secKey,clientUrl)){
// httpReq.getRequestDispatcher(/ intellixservices / activetime)。forward(httpReq,httpRes);
chain.doFilter(httpReq,httpRes);
} else {
httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED,未授权);
// httpReq.getRequestDispatcher(/ intellixservices / exception)。forward(httpReq,
// httpRes);
}
}
class:
// CORS实现
private String corsHeaders;
私人响应makeCORS(ResponseBuilder responseBuilder,弦乐returnMethod){
ResponseBuilder RB = responseBuilder.header(访问控制允许来源,*)
.header (Access-Control-Allow-Methods,GET,POST,OPTIONS);
if(!。equals(returnMethod)){
rb.header(Access-Control-Allow-Headers,returnMethod);
}
return rb.build();
}
私人回复makeCORS(ResponseBuilder responseBuilder){
return makeCORS(responseBuilder,corsHeaders);
}
@OPTIONS
公开回应getEmployee的(@HeaderParam(访问控制请求报头)字符串请求){
corsHeaders =请求;
return makeCORS(Response.ok(),request);
}
,然后返回
响应response = Response.status(404).build();
if(mf!= null){
response = makeCORS(Response.status(200).entity(mf));
} else {
response = makeCORS(Response.status(500));
}
返回响应;
我无法解决。请建议。
p>
这是我的jQuery调用:
< html>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = ISO-8859-1>
< script type =text / javascript
src =http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js>< ; / script>
< script type =application / javascript>
(函数($){
VAR URL =的http://本地主机:8888 / IntellixWebApi / intellixservices / dnareport / MTk3MC0wOS0wNFQwNjowNTowMA == / NDEuNTU4MTUyNSA = / LTczLjA1MTQ5NjYg / QW1lcmljYS9OZXdfWW9yaw == / MTpBOjB8QToxOjF8MToxOjE = / JSON ;
$ .ajax({
type:'GET',
url:url,
async:true,
contentType:'application / json ',
success:function(response){
alert(success);
},
error:function(xhr){
alert Status ='+ xhr.status +Message =+ xhr.statusText);
}
});
})(jQuery);
< / script>
< / head>
< body>
<! - 我们将在这里添加我们的HTML内容 - >
< / body>
< / html>
。我在web.xml中添加了CORS过滤器和java实用程序jar过滤器以及一些配置更改。这些链接是非常有帮助的。
的链接1
感谢大家的帮助。
I have one rest service deployed on Tomcat 7 and running. I can get the response data through browser, but when I tried it through jQuery it is showing an error. Please Check the snapshot.
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) req;
HttpServletResponse httpRes = (HttpServletResponse) res;
//System.out.println("Client Ip is : "+ SecurityFilter.getClientIpAddr(httpReq));
String domain = new URL(httpReq.getRequestURL().toString()).getHost();
//System.out.println("Domain is " + domain);
// referrer
String referrer = httpReq.getHeader("referer");
//System.out.println("Referral URL is -" + referrer);
// Security Key
String securityKey = httpReq.getParameter("secKey");
//System.out.println("Security Key Parameter " + securityKey);
// Origin
// No Origin header present means this is not a cross-domain request
String clientOrigin = httpReq.getHeader("Origin");
//System.out.println("Origin of the Request " + clientOrigin);
// CORS implementation
httpRes.addHeader("Access-Control-Allow-Origin", "*");
httpRes.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
// httpRes.addHeader("Access-Control-Allow-Origin", clientOrigin);
if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) {
httpRes.addHeader("Access-Control-Allow-Credentials", "true");
}
ValidateClient vl = new ValidateClient();
String secKey = "fmg_seckey"; //"SEC_1";;
String clientUrl = "fmggroup.com";//"www.xyzclient1.com";
// if request is coming from third party. Referral will be null if all
// request is from same server.
if (referrer != null) {
clientUrl = referrer.split("/")[2];
secKey = securityKey;
}
//System.out.println("Security Key " + secKey);
//System.out.println("Domain Name for the client " + clientUrl);
if (vl.isValidClient(secKey, clientUrl)) {
// httpReq.getRequestDispatcher("/intellixservices/activetime").forward(httpReq,httpRes);
chain.doFilter(httpReq, httpRes);
} else {
httpRes.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Not Authorised");
// httpReq.getRequestDispatcher("/intellixservices/exception").forward(httpReq,
// httpRes);
}
}
in the resource class:
// CORS implementation
private String corsHeaders;
private Response makeCORS(ResponseBuilder responseBuilder, String returnMethod) {
ResponseBuilder rb = responseBuilder.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
if (!"".equals(returnMethod)) {
rb.header("Access-Control-Allow-Headers", returnMethod);
}
return rb.build();
}
private Response makeCORS(ResponseBuilder responseBuilder) {
return makeCORS(responseBuilder, corsHeaders);
}
@OPTIONS
public Response getEmployee(@HeaderParam("Access-Control-Request-Headers") String request) {
corsHeaders = request;
return makeCORS(Response.ok(), request);
}
and then returning
Response response = Response.status(404).build();
if (mf != null) {
response = makeCORS(Response.status(200).entity(mf));
} else {
response = makeCORS(Response.status(500));
}
return response;
I am unable to resolve it. Please suggest.
This is my jQuery Call :-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="application/javascript">
(function($) {
var url = 'http://localhost:8888/IntellixWebApi/intellixservices/dnareport/MTk3MC0wOS0wNFQwNjowNTowMA==/NDEuNTU4MTUyNSA=/LTczLjA1MTQ5NjYg/QW1lcmljYS9OZXdfWW9yaw==/MTpBOjB8QToxOjF8MToxOjE=/json';
$.ajax({
type: 'GET',
url: url,
async: true,
contentType: 'application/json',
success: function(response) {
alert("success");
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
})(jQuery);
</script>
</head>
<body>
<!-- we will add our HTML content here -->
</body>
</html>
Any way I resolved the issue after a lot of googling. I added CORS filter and java utility jar filter and some configuration changes in the web.xml. These links are very helpful
Thanks you all for this great help.
这篇关于Jquery调用Java RESTful服务不工作CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!