Thursday, June 23, 2011

Request Parameters in JSTL

Display All Request Parameters in JSTL


The following piece of JSTL code displays all request parameters on the page,
except for check-boxes and radio-buttons. They require the use of the paramValues implicit object.
<c:forEach items="${param}" var="par">
        Parameter Name/Value : <c:out value="${par.key} - ${par.value}"/>
</c:forEach>
To display session and request objects, use the following code:
<c:forEach items="${sessionScope}" var="par">
        Session object name/value : <c:out value="${par.key} - ${par.value}"/>
</c:forEach>

<c:forEach items="${requestScope}" var="par">
        Request object name/value : <c:out value="${par.key} - ${par.value}"/>
</c:forEach>

Other implicit objects include pageScope, applicationScope, header, headerValues, initParam, cookie and pageContext.


Sorting Request Parameters


A java TreeMap class that implements
SortedMap
interface allows us to construct a sorted Map.
To sort request parameters, or any other implicit objects that implement the Map interface, I built a small bean class. Here is the source code listing:
    package beans;
    import java.util.Map;
    import java.util.TreeMap;

    public class SortMap{
    private Map map;

    public Map getMap() {
        return map;
    }
    public void setMap(Map map) {
        this.map = new TreeMap(map);
    }
}

The setMap method of the bean constructs a TreeMap object from the Map argument.

Now, it's easy to pass the map of request parameters to the new bean and obtain the key-value pairs from it:

 <jsp:useBean id="sorter" class= "beans.SortMap">
    <c:set target= "${sorter}" property="map" value="${param}"/>
</jsp:useBean>

<c:forEach items="${sorter.map}" var="par">
        Parameter name/value : <c:out value="${par.key} -  ${par.value}"/>
</c:forEach>