public
Enumeration<String> getHeaders(String name)
Returns
all the values of the specified request header as an Enumeration of
String objects.
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form method="get" action="/servlet/HelloWorld"> <input type="submit"> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.*; public class HelloWorld extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ try(PrintWriter out = res.getWriter()) { res.setContentType("text/html"); StringBuilder s1 = new StringBuilder(); Enumeration<String> headers = req.getHeaderNames(); while(headers.hasMoreElements()){ String headerName = headers.nextElement(); s1.append(headerName).append(":"); /* Get the Header Values */ Enumeration<String> headerValues = req.getHeaders(headerName); while(headerValues.hasMoreElements()){ s1.append(headerValues.nextElement()); } s1.append("<br />"); } String str = "<html>" + "<head>" + "<title> Hello World </title>" + "</head>" + "<body>" + "<h1> Headers are <br />" + s1 + "</h1> </body>" + "</html>"; out.println(str); } } }
No comments:
Post a Comment