Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

http - How to capture the requests using JAVA servlets

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...