use*_*716 63 java rest jax-rs jersey cors
I'm developing a java script client application, in server-side I need to handle CORS, all the services I had written in JAX-RS with JERSEY. My code:
@CrossOriginResourceSharing(allowAllOrigins = true)
@GET
@Path("/readOthersCalendar")
@Produces("application/json")
public Response readOthersCalendar(String dataJson) throws Exception {
//my code. Edited by gimbal2 to fix formatting
return Response.status(status).entity(jsonResponse).header("Access-Control-Allow-Origin", "*").build();
}
Run Code Online (Sandbox Code Playgroud)
As of now, i'm getting error No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."
Please assist me with this.
Thanks & Regards Buddha Puneeth
Pau*_*tha 146
注意:请务必阅读底部的更新
@CrossOriginResourceSharing 是一个CXF注释,所以它不适用于泽西岛.
使用Jersey来处理CORS,我通常只使用一个ContainerResponseFilter.所述ContainerResponseFilter用于泽西1和2是有点不同.既然你还没有提到你正在使用哪个版本,我会发布两个版本.
import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
@Provider
public class CORSFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext request,
ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用包扫描来发现提供程序和资源,则@Provider注释应该为您进行配置.如果没有,那么您将需要使用ResourceConfig或Application子类显式注册它.
用以下代码显式注册过滤器的示例代码ResourceConfig:
final ResourceConfig resourceConfig = new ResourceConfig();
resourceConfig.register(new CORSFilter());
final final URI uri = ...;
final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(uri, resourceConfig);
Run Code Online (Sandbox Code Playgroud)
对于Jersey 2.x,如果您在注册此过滤器时遇到问题,可以使用以下几种资源
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;
public class CORSFilter implements ContainerResponseFilter {
@Override
public ContainerResponse filter(ContainerRequest request,
ContainerResponse response) {
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Headers",
"origin, content-type, accept, authorization");
response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHttpHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
web.xml配置,你可以使用
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.yourpackage.CORSFilter</param-value>
</init-param>
Run Code Online (Sandbox Code Playgroud)
或者ResourceConfig你可以做到
resourceConfig.getContainerResponseFilters().add(new CORSFilter());
Run Code Online (Sandbox Code Playgroud)
或使用@Provider注释打包扫描.
请注意,上面的例子可以改进.您需要了解有关CORS如何工作的更多信息.请看这里.首先,您将获得所有回复的标题.这可能是不可取的.您可能只需要处理预检(或OPTIONS).如果您想查看更好的CORS过滤器,可以查看RESTeasy的源代码CorsFilter
所以我决定添加一个更正确的实现.上面的实现是惰性的,并将所有CORS头添加到所有请求中.另一个错误是,它只是一个响应过滤器,请求仍然是进程.这意味着当预检请求进入时,这是一个OPTIONS请求,将没有实现OPTIONS方法,因此我们将得到405响应,这是不正确的.
这是它应该如何工作.因此,有两种类型的CORS请求:简单请求和预检请求.对于简单的请求,浏览器将发送实际请求并添加Origin请求标头.浏览器期望响应具有Access-Control-Allow-Origin标头,表示Origin允许来自标头的原点.为了将其视为"简单请求",它必须符合以下标准:
AcceptAccept-LanguageContent-LanguageContent-TypeDPRSave-DataViewport-WidthWidthContent-Type标头唯一允许的值是:
application/x-www-form-urlencodedmultipart/form-datatext/plain如果请求不符合所有这三个标准,则会发出预检请求.这是在发出实际请求之前对服务器发出的OPTIONS请求.它将包含不同的Access-Control-XX-XX标头,服务器应该使用自己的CORS响应标头响应这些标头.以下是匹配的标题:
Preflight Request and Response Headers
+-----------------------------------+--------------------------------------+
| REQUEST HEADER | RESPONSE HEADER |
+===================================+======================================+
| Origin | Access-Control-Allow-Origin |
+-----------------------------------+--------------------------------------+
| Access-Control-Request-Headers | Access-Control-Allow-Headers |
+-----------------------------------+--------------------------------------+
| Access-Control-Request-Method | Access-Control-Allow-Methods |
+-----------------------------------+--------------------------------------+
| XHR.withCredentials | Access-Control-Allow-Credentials |
+-----------------------------------+--------------------------------------+
Run Code Online (Sandbox Code Playgroud)
使用Origin请求标头,该值将是源服务器域,并且响应Access-Control-Allow-Header应该是相同的地址或*指定允许所有源.
如果客户端尝试手动设置不在上面列表中的任何标头,则浏览器将设置Access-Control-Request-Headers标头,其值为客户端尝试设置的所有标头的列表.服务器应该使用Access-Control-Allow-Headers响应头响应,其值是它允许的头列表.
浏览器还将设置Access-Control-Request-Method请求标头,其值为请求的HTTP方法.服务器应该响应Access-Control-Allow-Methods响应头,值是它允许的方法列表.
如果客户端使用XHR.withCredentials,则服务器应响应Access-Control-Allow-Credentials响应头,值为true.在这里阅读更多.
所以尽管如此,这是一个更好的实现.即使这比上面的实现更好,它仍然不如我链接的RESTEasy,因为这个实现仍然允许所有的起源.但是这个过滤器比上面的过滤器更好地遵守CORS规范,而过滤器只是将CORS响应头添加到所有请求中.请注意,您可能还需要修改Access-Control-Allow-Headers以匹配应用程序允许的标头; 您可能希望在此示例中添加或删除列表中的某些标头.
@Provider
@PreMatching
public class CorsFilter implements ContainerRequestFilter, ContainerResponseFilter {
/**
* Method for ContainerRequestFilter.
*/
@Override
public void filter(ContainerRequestContext request) throws IOException {
// If it's a preflight request, we abort the request with
// a 200 status, and the CORS headers are added in the
// response filter method below.
if (isPreflightRequest(request)) {
request.abortWith(Response.ok().build());
return;
}
}
/**
* A preflight request is an OPTIONS request
* with an Origin header.
*/
private static boolean isPreflightRequest(ContainerRequestContext request) {
return request.getHeaderString("Origin") != null
&& request.getMethod().equalsIgnoreCase("OPTIONS");
}
/**
* Method for ContainerResponseFilter.
*/
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response)
throws IOException {
// if there is no Origin header, then it is not a
// cross origin request. We don't do anything.
if (request.getHeaderString("Origin") == null) {
return;
}
// If it is a preflight request, then we add all
// the CORS headers here.
if (isPreflightRequest(request)) {
response.getHeaders().add("Access-Control-Allow-Credentials", "true");
response.getHeaders().add("Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS, HEAD");
response.getHeaders().add("Access-Control-Allow-Headers",
// Whatever other non-standard/safe headers (see list above)
// you want the client to be able to send to the server,
// put it in this list. And remove the ones you don't want.
"X-Requested-With, Authorization, " +
"Accept-Version, Content-MD5, CSRF-Token");
}
// Cross origin requests can be either simple requests
// or preflight request. We need to add this header
// to both type of requests. Only preflight requests
// need the previously added headers.
response.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}
Run Code Online (Sandbox Code Playgroud)
要了解有关CORS的更多信息,我建议您阅读有关跨源资源共享(CORS)的MDN文档
删除注释“ @CrossOriginResourceSharing(allowAllOrigins = true)”
然后返回如下响应:
return Response.ok()
.entity(jsonResponse)
.header("Access-Control-Allow-Origin", "*")
.build();
Run Code Online (Sandbox Code Playgroud)
但是jsonResponse应该用POJO对象代替!
Mic*_*el 5
另一个答案可能严格正确,但会产生误导。缺少的部分是您可以将来自不同来源的过滤器混合在一起。即使认为Jersey可能不提供CORS过滤器(不是我检查过的事实,但我相信其他答案),您也可以使用tomcat自己的CORS过滤器。
我在Jersey上成功使用了它。例如,我有自己的基本身份验证过滤器实现,以及CORS。最好的是,CORS过滤器是在Web XML中而不是在代码中配置的。
| 归档时间: |
|
| 查看次数: |
69101 次 |
| 最近记录: |