5

I want to loop through an enumeration containing all of the header names inside a java servlet. My code is as follows:

public class ServletParameterServlet extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        ServletConfig c = this.getServletConfig();
        PrintWriter writer = response.getWriter();

        writer.append("database: ").append(c.getInitParameter("database"))
              .append(", server: ").append(c.getInitParameter("server"));

       Enumeration<String> headerNames = ((HttpServletRequest) c).getHeaderNames();


    }
}

Is this the correct syntax? How does one actually iterate over an enums values in Java? And specifically in this instance?

Thanks for your help, Marc

Dewey Banks
  • 323
  • 1
  • 7
  • 19

3 Answers3

11

It's just an iteration like normal Java:

for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) {
    String nextHeaderName = (String) e.nextElement();
    String headerValue = request.getHeader(nextHeaderName);
}

Note that for some setups this is a bit dangerous in that HTTP headers can be duplicated. In that case, the headerValue will be only the first HTTP header with that name. Use getHeaders to get all of them.

And throw away whatever Eclipse was suggesting - it's garbage.

stdunbar
  • 16,263
  • 11
  • 31
  • 53
1

we can use forEachRemaining

    Enumeration<String> headerNames = request.getHeaderNames();
    headerNames.asIterator().forEachRemaining(header -> {
         System.out.println("Header Name:" + header + "   " + "Header Value:" + request.getHeader(header));
    });
Walterwhites
  • 1,287
  • 13
  • 9
1

You can convert it to List by using the following method:

public static <T> List<T> enumerationToList(final Enumeration<T> enumeration) {
    if (enumeration == null) {
        return new ArrayList<>();
    }
    return Collections.list(enumeration);
}

usage:

final List<String> headerNames = enumerationToList(request.getHeaderNames());

for (final String headerName : headerNames) {
    System.out.println(headerName);
}
Shadi Abu Hilal
  • 281
  • 1
  • 3
  • 7