Thursday 21 August 2014

setHeader (String name, String value)

public void setHeader(String name, String value)
Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.

Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   
     <title>set Header</title>
    </head>
    <body>
        <form method="get" action="/servlet/SetHeader">
            <input type="submit" value ="Get Data">
        </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>SetHeader</servlet-name>
        <servlet-class>SetHeader</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SetHeader</servlet-name>
        <url-pattern>/SetHeader</url-pattern>
    </servlet-mapping>
</web-app>

SetHeader.java
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;

public class SetHeader extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
        try(PrintWriter out = res.getWriter()){
            res.setContentType("text/html");
            res.setHeader("Refresh", "5; URL=https://self-learning-java-tutorial.blogspot.com/2014/02/blog-post.html");
            try{
                Thread.sleep(10000);
            }
            catch(InterruptedException e){
                
            }
        }
    }
}


Note:
Using refresh header we can instruct a web browser to automatically refresh the current web page or frame after a given time interval.





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment