Redirect a Page or URL using javascript - Java @ Desk

Tuesday, December 31, 2013

Redirect a Page or URL using javascript

Redirect a Page or URL using javascript

What is Redirect?
Redirect is something, the user requests for some JSP page but internally the user gets redirected to some other page within the application or outside the application.

Reasons for redirect:
1) Domain Name change - There arise a case where a registered domain need to be changed. In that case, the JSP pages that are build up need to be redirected to a new domain so that users do not see the old website.

2) Single Domain Usage - Every application uses domain region wise. Like for India, URL will end with ".in". In order to keep all the users at ".com" domain, redirect comes into usage

3) Payment Gateways - During online bill payments, the application needs to be redirected to third party payment sites. Consider you want to pay Vodafone Bill. So as soon as you fill in all the details and proceed to payment, the website redirects to a third party website for payment process. Here redirects comes into picture.

This side of redirection is termed as Client Side Redirect since it happens through Javascript which occurs at browser side.

There are different ways to implement the Redirection using Javascript:
1) window.localtion.replace - The replace method on the other hand navigates to the URL without adding a new record to the history. You cannot click the back button in this case
2) window.localtion.href - Work like assign
3) window.localtion.assign - The assign method does add a new record to the history.
4) window.location - Work like assign

Sample implementation for JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="redirect">
<h2>Redirecting to another Page</h2>
</div>
<script>
 // JavaScript using localtion.replace
 window.location.replace("http://javacodeimpl.blogspot.com");
 // JavaScript using localtion.href
 //window.location.href="http://javacodeimpl.blogspot.com";
 // JavaScript using localtion.assign
 //window.location.assign("http://javacodeimpl.blogspot.com");
</script>
</body>
</html>







No comments:

Post a Comment