I'm trying to log the request body from embedded jetty-server.
I successfully get the body of the POST-request (mainly from https://stackoverflow.com/a/19547549/8916463 and https://stackoverflow.com/a/8972088/8916463)
public class JettyFilter {
public static void main(final String[] args) throws Exception {
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
handler.addFilterWithMapping(WebServerLoggingFilter .class, "/*",
EnumSet.of(DispatcherType.REQUEST));
server.start();
server.join();
}
public static class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getReader().lines()
.collect(Collectors.joining(System.lineSeparator())));
}
}
public static class WebServerLoggingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("hello from filter");
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
@Override
public void destroy() {}
}
}
The problem is that the POST-requests from the controllers are not called at all when I configure server this way. But they are properly called when I try logging using NCSA logging, (in such case request body is not logged):
NCSARequestLog requestLog = new NCSARequestLog(os.getDatedFilename());
requestLog.setExtended(true);
RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog(requestLog);
requestLog.setAppend(true);
HandlerList mainHandlers = new HandlerList();
mainHandlers.addHandler(accessHandler);
mainHandlers.addHandler(new DefaultHandler());
requestLogHandler.setHandler(mainHandlers);
HandlerList topLevelHandlers = new HandlerList();
topLevelHandlers.addHandler(requestLogHandler);
server.setHandler(topLevelHandlers);
My goal is to log the body of the request to some file.
Apparently I miss something very simple and logging of the requests body can be implemented much easier.
PS. Spring is not used.
Any help will be deeply appreciated!