javajettyembedded-jettyjetty-9

Configure Jetty to run a custom filter before filters in war file's web.xml run


I have a third party .war file that I run on a Jetty server. I need to run code for logging purposes before the filters defined in the .war file's deployment descriptor run. The code needs to have access to the incoming request and the response object and to the context of the logger that runs for the app in the war.

Is there a way to do this in Jetty's xml configuration file? I don't want to touch the war file due to concerns about license.

I could override the deployment descriptor which would allow me to add custom filters but I believe these would then run after the filters in the war. I could also use a request customizer but that doesn't give me access to the response which I also need to edit.

I tried adding a handler to a HandlerCollection before the handler with the org.eclipse.jetty.webapp.WebAppContext that runs the war but it doesn't seem that I have access to the web app's logger's context...

Is there any way to do this? So before the web app's servlet executes run a piece of code that can access the incoming request and the response and the web app's context?


Solution

  • Option 1:

    To access the raw Request and Response at the various stages of their lifecycles, use the HttpChannel.Listener (make sure you read the javadoc/apidoc to understand what each event means).

    Option 2:

    To add a handler in the WebAppContext, before the Session/Security handling, but after other handlers, use WebAppContext.insertHandler(HandlerWrapper).

    Option 3:

    Create a web-fragment servlet jar that represents your servlet Filter, and add it to the WebAppContext.setExtraClassPath(String), which will be picked up and added to the actual webapp's startup.

    Option 4:

    Create a custom RequestLog implementation (that you add to Server.setRequestLog(RequestLog) that is notified once the request AND response are complete, so you can log the state of the request/log to whatever source you want.

    Option 5:

    Use one of the existing RequestLog implementations to log the details you desire to the console in the format you desire. (Look at the combination of CustomRequestLog and Slf4jRequestLogWriter)