Thursday, 31 July 2014

getHeader (String name)

public String getHeader(String name)
Returns the value of the specified request header as a String. If there are multiple headers with the same name, this method returns the first head in the request.

<%@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 */
                s1.append(req.getHeader(headerName)).append("<br />");                
            }
            
            String str = "<html>" +
                         "<head>" +
                         "<title> Hello World </title>" +
                         "</head>" +
                         "<body>" +
                         "<h1> Headers are <br />" + s1 +
                         "</h1> </body>" +
                         "</html>";
            out.println(str);
       }
   } 
  
}

Output




 
Prevoius                                                 Next                                                 Home

No comments:

Post a Comment