Skip to content

Instantly share code, notes, and snippets.

@linyatis
Created November 6, 2014 00:44
Show Gist options
  • Select an option

  • Save linyatis/90097655aed8f289036c to your computer and use it in GitHub Desktop.

Select an option

Save linyatis/90097655aed8f289036c to your computer and use it in GitHub Desktop.
VRaptor 4 CORS
@Controller
public class CORSController {
@Inject private Result result;
@Inject private Router router;
@Options("/*")
public void options(@Observes VRaptorRequestStarted requestInfo) {
Set<HttpMethod> allowed = router.allowedMethodsFor(requestInfo.getRequest().getRequestedUri());
String allowMethods = allowed.toString().replaceAll("\\[|\\]", "");
result.use(Results.status()).header("Allow", allowMethods);
result.use(Results.status()).header("Access-Control-Allow-Methods", allowMethods);
result.use(Results.status()).header("Access-Control-Allow-Headers", "Content-Type, X-Requested-With, accept, Authorization, origin");
}
}
@Intercepts
public class CORSInterceptor {
@Inject private Result result;
@Inject private HttpServletRequest request;
@BeforeCall
public void intercept() throws InterceptionException {
String origin = request.getHeader("origin") != null ? request.getHeader("origin") : "*";
result.use(Results.status()).header("Access-Control-Allow-Origin", origin);
result.use(Results.status()).header("Access-Control-Allow-Credentials", "true");
result.use(Results.status()).header("Access-Control-Expose-Headers", "Content-Type, Location");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment