I use Jetty 9 and have some problems with configuration. I simple RESTs works fine. But the problem begun when I tried to add new headers to all requests and error handler. Only way I am able to handle headers it is by adding this code to every response:
return Response.ok(murals)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.build();
Server configuration:
Server server = new Server(9998);
ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
servletContextHandler.addServlet(DefaultServlet.class, "/");
ResourceConfig rc = new ResourceConfig()
.register(FilterHeaders.class)
.register(ExceptionNotFound.class)
.register(CORSFilter.class); //doesnt work
new ServletHolder(new ServletContainer(rc));
HandlerWrapper han = new HandlerWrapper();
han.setHandler(new AbstractHandler() {
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setAttribute("welcome","Hello"); //doesn't work
}
});
servletContextHandler.addFilter(Filters.class, "/*", EnumSet.of(DispatcherType.REQUEST)); //doesnt work
ResourceHandler resourceHandler = resourceHandler();
servletContextHandler.setHandler(resourceHandler);
servletContextHandler.setHandler(han);
server.start();
server.join();
CROSFilter class
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;
}
}
How to register headers? What am I doing wrong? I do not use WEB configuration.