Search code examples
javaservletsweb-applicationsapplication-serverspecifications

Is it portable to reference the request parameter map after a request-cycle?


I'd like to know if its conform to the java servlet specification 2.5 to reference/save the return value of request.getParameterMap() between requests.

The final specification only states at page 203:

Returns: an immutable java.util.Map containing parameter names as keys and parameter values as map values. The keys in the parameter map are of type String. The values in the parameter map are of type String array.

But it's not clear to me:

  • if the Map is only immutable to the application, not to the application server

  • if it's allowed that the application server may re-use the instance for another request (for example, if the parameters and their values are the same as in the previous request)

EDIT: The reason for this: I'd like to save the request map of each request and in case of an error to print them out for diagnostic purposes.


Solution

  • if the Map is only immutable to the application, not to the application server

    It's immutable in the API, yes. It also makes sense, what's the point of changing the request parameter map? The servletcontainer implementation in turn can of course hold of a mutable map of it "behind the scenes". But you should not worry about the implementation specific details.

    if it's allowed that the application server may re-use the instance for another request (for example, if the parameters and their values are the same as in the previous request)

    No, the server doesn't do that. It just creates a new one. The parameters are bound to a specific request.

    If you want to collect the parameters of every request during a session, then you need to do this yourself. The best place for this would be a Filter.

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest hsr = (HttpServletRequest) request;
        List<Map<String, String[]>> allParameters = (List<Map<String, String[]>>) hsr.getSession().getAttribute("allParameters");
        if (allParameters == null) {
            allParameters = new ArrayList<Map<String,String[]>>();
            hsr.getSession().setAttribute("allParameters", allParameters);
        }
        allParameters.add(hsr.getParameterMap());
        chain.doFilter(request, response);
    }