Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through an Enumeration containing Header Names in Java Servlet

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

like image 757
Dewey Banks Avatar asked Sep 16 '17 06:09

Dewey Banks


3 Answers

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.

like image 127
stdunbar Avatar answered Nov 01 '22 20:11

stdunbar


we can use forEachRemaining

    Enumeration<String> headerNames = request.getHeaderNames();
    headerNames.asIterator().forEachRemaining(header -> {
         System.out.println("Header Name:" + header + "   " + "Header Value:" + request.getHeader(header));
    });
like image 39
Walterwhites Avatar answered Nov 01 '22 20:11

Walterwhites


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);
}
like image 1
Shadi Abu Hilal Avatar answered Nov 01 '22 20:11

Shadi Abu Hilal