Thursday, December 31, 2009

Redirecting permanently in HttpServlet from your old domain (website) to new domain

Let us assume we face a scenario where we move from a old domain (website) to a new domain (website). You may do this when you expand your business offering and the old name may not be appropriate.
But your old domain has gained reputation (like a good page rank and a number of incoming links) which you wish to carry forward to your new domain. One way of doing this is respond with HTTP code 301 which is permanently moved.
You may also make use of use Google web master tools to inform the change in domain address (as Google is currently the #1 search engine ). This will prevent the decrease in hits to your website from search engines.
The below code shows how to implement it if you host a Java web application for your old domain.
In web.xml make the below entry.
01xml version="1.0" encoding="UTF-8"?>
03 <servlet>
04 <servlet-name>RedirectionServletservlet-name>
05 <servlet-class>com.olddomain.web.servlet.RedirectionServletservlet-class>
06 servlet>
07 <servlet-mapping>
08 <servlet-name>RedirectionServletservlet-name>
09 <url-pattern>/*url-pattern>
10 servlet-mapping>
11 web-app>
Next the code for
01package com.olddomain.web.servlet;
04import javax.servlet.ServletException;
05import javax.servlet.http.HttpServlet;
06import javax.servlet.http.HttpServletRequest;
07import javax.servlet.http.HttpServletResponse;
09public class RedirectionServlet extends HttpServlet {
11 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
12 throws ServletException, IOException {
14 //Get the incoming URL request.
15 response.setHeader("Location",""+request.getRequestURI());
16 response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
17 }
19 @Override
20 protected void doGet(HttpServletRequest request, HttpServletResponse response)
21 throws ServletException, IOException {
22 processRequest(request, response);
23 }
25 @Override
26 protected void doPost(HttpServletRequest request, HttpServletResponse response)
27 throws ServletException, IOException {
28 processRequest(request, response);
29 }
Note: Using response.sendRedirect will produce only HTTP status code 302 which is temporarily moved and not 301 which indicates it is permanently moved.

1 comment:

Anonymous said...

Good post and this enter helped me alot in my college assignement. Say thank you you seeking your information.