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
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.
we can use forEachRemaining
Enumeration<String> headerNames = request.getHeaderNames();
headerNames.asIterator().forEachRemaining(header -> {
System.out.println("Header Name:" + header + " " + "Header Value:" + request.getHeader(header));
});
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With