Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
230 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...