Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to request.getParameterNames into List of strings?

Tags:

java

servlets

Is it possible to get request.getParameterNames() as a list of Strings? I need to have it in this form.

like image 999
SSV Avatar asked Jun 24 '13 17:06

SSV


People also ask

How to use getParameterNames in servlet?

getParameterNames. Returns an Enumeration of String objects containing the names of the parameters contained in this request. If the request has no parameters, the method returns an empty Enumeration .

Do servlets getParameterNames always return?

java - Servlet request. getParameter() always return null value - Stack Overflow.

How to get names of the parameters in servlet?

By calling request. getParameterNames() you will get an Enumeration object by iterating this object you can get the parameter names. When you call the servlet and pass some parameters you get the parameter name echoed on the web browser.

What does getParameter return?

getParameter. Returns the value of a request parameter as a String , or null if the parameter does not exist. Request parameters are extra information sent with the request. For HTTP servlets, parameters are contained in the query string or posted form data.


2 Answers

Just construct a new ArrayList wrapping the keyset of the request parameter map.

List<String> parameterNames = new ArrayList<String>(request.getParameterMap().keySet());
// ...

I only wonder how it's useful to have it as List<String>. A Set<String> would make much more sense as parameter names are supposed to be unique (a List can contain duplicate elements). A Set<String> is also exactly what the map's keyset already represents.

Set<String> parameterNames = request.getParameterMap().keySet();
// ...

Or perhaps you don't need it at all for the particular functional requirement for which you thought that massaging the parameter names into a List<String> would be the solution. Perhaps you actually intented to iterate over it in an enhanced loop, for example? That's also perfectly possible on a Map.

for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
    String name = entry.getKey();
    String value = entry.getValue()[0];
    // ...
}
like image 188
BalusC Avatar answered Sep 29 '22 15:09

BalusC


It is possible to getParameterNames from servlets by using HttpServletRequest.getParameterNames() method. This returns an enumeration. We can cast the enemeration elements into string and add those into an ArrayList of parameters as follows.

 ArrayList<String> parameterNames = new ArrayList<String>();
 Enumeration enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String parameterName = (String) enumeration.nextElement();
        parameterNames.add(parameterName);
    }

 // you can do whatever you want to do with parameter lists..
like image 36
Prasad Kharkar Avatar answered Sep 29 '22 14:09

Prasad Kharkar