Getting a 403 on root requests when using a ResourceHandler and custom handler in Jetty

前端 未结 2 1459
暗喜
暗喜 2021-01-19 06:19

In (embedded) Jetty, I\'m trying to use a ResourceHandler to serve static files and a custom handler to respond to dynamic requests. Based on this page I have a setup that l

2条回答
  •  深忆病人
    2021-01-19 07:00

    Jetty tries each Handler sequentially until one of the handlers calls setHandled(true) on the request. Not sure why ResourceHandler doesn't do this for "/".

    My solution was to reverse the order in which you list the handlers so that yours is called first. Then check for the special case "/" in the URL. If you'd like to pass the request on to the ResourceHandler, simply return without declaring the request as handled.

    Declare the order of handlers like this:

    Server server = new Server(8080);
    
    CustomHandler default = new CustomHandler();
    default.setServer(server);
    
    ResourceHandler files = new ResourceHandler();
    files.setServer(server);
    files.setResourceBase("./path/to/resources");
    
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] {default, files});
    
    server.setHandler(handlers);
    
    server.start();
    server.join();
    

    And define CustomHandler's handle method like this:

    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        if(!request.getRequestURI().equals("/")){
            return;
        }
        // Do Stuff...
        baseRequest.setHandled(true);
        return;
    }
    

    I agree it would be most elegant to have ResourceHandler simply yield on "/" instead of handling the response with a 403.

提交回复
热议问题