Thursday 21 August 2014

Redirecting request

void sendRedirect(String location) throws IOException
sendRedirect method stop further processing of the request and send http status code "301" and URL of the location to be redirected to the client browser in the response header. Server does not have control of this request after sending the redirect related HTTP header to the client browser. Client browser sees http status 301 and then it know it should send a new request to the url in "Location" http header which is set by server. and Client browser sends a new request to the new URL and it will be processed by the server as another normal request.

As per HTTP specification
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

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/SendRedirect">
            <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>SendRedirect</servlet-name>
        <servlet-class>SendRedirect</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SendRedirect</servlet-name>
        <url-pattern>/SendRedirect</url-pattern>
    </servlet-mapping>
</web-app>

SendRedirect.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SendRedirect extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{    
        res.sendRedirect("https://self-learning-java-tutorial.blogspot.com/2014/02/blog-post.html");
    }
}





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment