开发者

How do I iterate over request.getParamterNames()?

I'm using Grails 1.2.1. Within a Grails method that references the HttpServletRequest object, how do I iterate over the request.getPara开发者_如何学运维meterNames() enumeration? This doesn't work ...

    protected void doCacheTransport(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {               
            def url = request.getParameter("url")
            request.getParameterNames().each { 
                def paramName = it
                if (paramName != "url") { 
                    remoteUrl << "&" << paramName << "=" << request.getParameter(paramName)
                }   // if
            }   // each

I included the 'def url = request.getParameter("url")' line in my debugger to prove to myself that the parameter "url" indeed is defined. However, the loop skips over everything.

Thanks for any additional info. - Dave


I'm not quite sure why your code isn't working, since it looks OK (assuming that remoteUrl is declared outside of the each closure. In any case, this can be simplified quite a bit. First, by leveraging the getParameterMap() method of ServletRequest and second, by using the obscure but very powerful inject method from the Groovy collections API.

Inject takes an initial value (which I'm presuming you set remoteUrl to in your actual code), and then iterates over a collection, passing an accumulated value (or the initial value on the first pass through), and the item. This is very convenient for calculating a value whose result is somehow derived from every element in a collection.

That said, I think you can do something like this to get the result you want:

protected void doCacheTransport(HttpServletRequest request, HttpServletResponse response) {
    def remoteUrl = request.parameterMap.entrySet().inject('http://someurl.example.com/?key=1828372') { url, entry ->
        if (entry.key == "url") return url
        else url << "&${entry.key}=${entry.value}"
    }
    // ...

}

If you can provide more details on what, exactly you are doing, I can provide a more helpful example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜