是否可以使用JAX-RS(Jersey)低音注释来注释@CrossOrigin(Spring-MVC)?
You can create something like that by implementing ContainerRequestFilter
and ContainerResponseFilter
(see: Filters ) with Annotation driven Name binding or Dynamic binding .
Here an Annotation
you could use for Name or Dynamic binding:
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface CrossOrigin {
String origins();
}
Here is an incomplete example of a DynamicFeature
implementation containing and registering the filter classes in dynamic manner:
import org.glassfish.jersey.server.model.AnnotatedMethod;
import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Priorities;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
@Provider
public class CrossOriginDynamicFeature implements DynamicFeature {
//check annotation, register filters if CrossOrigin is present (DynamicBinding)
@Override
public void configure(final ResourceInfo resourceInfo, final FeatureContext configuration) {
final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod());
if (resourceInfo.getResourceClass().getAnnotation(CrossOrigin.class) != null) {
configuration.register(CrossOriginFilter.class);
configuration.register(ResponseCorsFilter.class);
}
}
//this filter handles the request and checks the origin given
@Priority(Priorities.AUTHENTICATION)
private static class CrossOriginFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest httpRequest;
@Context
private ResourceInfo resourceInfo;
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
String origins = resourceInfo.getResourceMethod().getDeclaredAnnotation(CrossOrigin.class).origins();
String originHeader = requestContext.getHeaderString("origin");
//Maybe you want a different behaviour here.
//To prevent the execution of the annotated resource method
//if the origin of the request is not in the specified list,
//we break the execution with a 401.
if (Arrays.asList(origins.split(",")).contains(originHeader)) {
throw new WebApplicationException(Response.Status.UNAUTHORIZED);
}
}
}
//if the Request filter allows the access,
//the CORS header are added to the response here.
//There are other stackoverflow questions regarding this theme.
public class ResponseCorsFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
//... add CORS header
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.