How to capture the requests using JAVA servlets

2019-10-03 04:24发布

问题:

I need to capture all the http/https requests that are going through the browsers of my system using JAVA servlets.

Can I achieve that?

回答1:

going through the browsers of my system You can do this is with an implementation of ServletRequestListener::requestInitialized(ServletRequestEvent sre)

The Documentation say:

requestInitialized(ServletRequestEvent sre)
Receives notification that a ServletRequest is about to come into scope of the web application.

The class could look like this:

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Map.Entry;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener
public class RequestListener implements ServletRequestListener {
    public RequestListener() {}

    public void requestDestroyed(ServletRequestEvent sre)  {}

    public void requestInitialized(ServletRequestEvent sre)  {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        System.out.println("Timestamp: " + new Timestamp(System.currentTimeMillis()));
        System.out.println("SessionId: " + request.getSession(false));
        System.out.println("RequestURL: " + request.getRequestURL());
        System.out.println("Method: " + request.getMethod());

        System.out.println("Parameters: ");
        for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            System.out.println(entry.getKey() + " = " + Arrays.asList(entry.getValue()));
        }
    }
}

In the console you get something like this:

Timestamp: 2017-01-25 19:12:04.36
SessionId: null
RequestURL: https://localhost:8181/jee6/ResponseFilterTest/Fiz
Method: GET
Parameters:
p1 = [v1]
p2 = [v2]

Instead in the console you can store the data in a DB or write to a log.

If you need to differentiate between local and remote requests you can use request.getRemoteAddr(). For local requests it is 127.0.0.1