Getting a Request Header in a Servlet - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

Getting a Request Header in a Servlet


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // Get the value of a request header; the name is case-insensitive
    String name = "user-agent";
    String value = req.getHeader(name);
    if (value == null) {
        // The request header was not present
    }
    // Get all request headers
    Enumeration enum = req.getHeaderNames();
    for (; enum.hasMoreElements(); ) {
        // Get the name of the request header
        name = (String)enum.nextElement();
        out.println(name);

        // Get a value of the request header
        value = req.getHeader(name);

        Enumeration valuesEnum = req.getHeaders(name);
        for (; valuesEnum.hasMoreElements(); ) {
            // Get a value of the request header
            value = (String)valuesEnum.nextElement();

            out.println("    "+value);
        }
    }
    out.close();
}

Related Tutorials