Servlets - Page Redirection


Page redirection is where the customer is sent to another area other than asked. Page redirection is commonly utilized when a report moves to another area or might be a direct result of burden balancing.

The easiest method for diverting a demand to another page is utilizing technique sendRedirect() of reaction object. Following is the mark of this strategy −

public void HttpServletResponse.sendRedirect(String location) 

throws IOException 

This technique sends back the reaction to the program alongside the status code and new page area. You can likewise utilize setStatus() and setHeader() techniques together to accomplish the equivalent −

.... 

String site = "http://www.newpage.com" ; 

response.setStatus(response.SC_MOVED_TEMPORARILY); 

response.setHeader("Location", site); 

.... 

Example

This model shows how a servlet performs page redirection to another area −

import java.io.*; 

import java.sql.Date; 

import java.util.*; 

import javax.servlet.*; 

import javax.servlet.http.*; 

public class PageRedirect extends HttpServlet { 

public void doGet(HttpServletRequest request, HttpServletResponse response) 

throws ServletException, IOException { 

//Set reaction content type 

response.setContentType("text/html"); 

//New area to be redirected 

String site = new String("http://www.welookups.com"); 

response.setStatus(response.SC_MOVED_TEMPORARILY); 

response.setHeader("Location", site); 

} 

} 

Now let us incorporate above servlet and make following passages in web.xml

.... 

<servlet> 

<servlet-name>PageRedirect</servlet-name> 

<servlet-class>PageRedirect</servlet-class> 

</servlet> 

<servlet-mapping> 

<servlet-name>PageRedirect</servlet-name> 

<url-pattern>/PageRedirect</url-pattern> 

</servlet-mapping> 

....

Now call this servlet utilizing URL http://localhost:8080/PageRedirect. This would divert you to URL http://www.welookups.com.






© Javacodegeeks 2018 -
All Right Reserved and you agree to have read and accepted our term and condition.

Python 3