Changing domain names, redirect each JSF page to corresponding page in new domain using a JSF Filter

When changing domain names, Google recommends that redirection is done page by page in order to preserve page search rank. Below is how to redirect pages of a Java Server Faces (JSF) application to corresponding pages of a new domain name using a JSF Filter.

In JSF applications, Filters are executed before any page is rendered making it the best place to do redirection.

In Netbeans you create a Filter through its add/new file facility, selecting filter as file new file type. A ready to use stub will then be created for you. All you need is edit the doFilter method. Your web.xml will also be updated with the new created filter. Below is how the entry of your filter in your web.xml looks like. Please note that "Redirect" is the name I use with my own filter. Use any desired name.


    <filter>
        <filter-name>Redirect</filter-name>
        <filter-class<package-name.Redirect</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Redirect</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

A similar feature should also be available in Eclipse and other IDE's.

Option 1. Passthrough without prompts.


    public void doFilter(ServletRequest request, 
            ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        String params = req.getQueryString();        	

        // this is your new domain	
        String url = "http://your-new-domain-name.com"; 	   
        
        url += uri;
        
        if (params != null) {
            url += ("?"+params);
        }
       
        resp.setStatus(301);
        resp.sendRedirect(url);

    }

When you need to tell your user that a redirection is about to happen, sometimes you need to prompt the user or redirect with a message.

Option 2: Prompt user. Replace last two lines in Option 1 above with the code below.

 
        
        resp.setContentType("text/html");
        ServletOutputStream out = resp.getOutputStream();
         
        out.println("<html>");               
        out.println("<body>");
        out.println("<br/>");     
        out.println("Your message");                
        out.println("<a href='"+url+"'><h3>"+url+"</h3></a>");
        
        out.println("<br/>");                        
        out.println("</body>");
        out.println("</html>");
                           
        out.flush();
                
        out.close();
        

If you are using Netbeans press ctrl-alt-i to include required imports.

Good luck.

If you like the article, please share.
(Site URL pattern has changed as a result social actions counter was reset.)



Comment icon   Comments (Newest first)