Loop through an Enumeration containing Header Names in Java Servlet
Asked Answered
T

3

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

Togetherness answered 16/9, 2017 at 6:18 Comment(2)
What are you trying to achieve when you cast a ServletConfig to a HttpServletRequest?Subclavius
That was eclipses suggestion :) It doesn't make sense to me.Togetherness
A
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.

Admissive answered 18/9, 2017 at 20:46 Comment(0)
T
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));
    });
Thievery answered 6/12, 2019 at 15:26 Comment(0)
S
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);
}
Saintmihiel answered 21/2, 2020 at 3:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.