javaservletsservlet-listeners

How to get URL specific details and Request Type(GET, POST, PUT) from ServletRequestEvent?


I am implementing ServletRequestListener and overriding its methods requestInitialized and requestDestroyed.

When requestDestroyed is called, I want to know details like whether the request is a GET/POST request and the parameters sent along with it. What should be the approach?

public void requestDestroyed(ServletRequestEvent event) {
    ServletRequest s = event.getServletRequest();
    //use this to get those details

Solution

  • From the ServletRequestEvent passed to the ServletRequestListener you implemented, call getServletRequest to get a ServletRequest object. Then cast to the subinterface, HttpServletRequest.

    From there you can interrogate for parts of the URL. See this post for a handy diagram of the various parts of a URL mapped to various methods on that class.

    public void requestDestroyed(ServletRequestEvent event) {
        ServletRequest s = event.getServletRequest();
        HttpServletRequest request = (HttpServletRequest) s;  // Cast to subinterface.
    
        String method = request.getMethod();
        Map<String,String[]> parameters = request.getParameterMap();
    }