Java - How to insert www in naked domain?

UPDATED: 23 May 2013

Lets consider you want to insert www in url forcefully for certain reasons. Its easy task you can handle by simple script that I'm gonna give you. Keep in mind you need to change the below code for your domain as per your need.

Scenario: I'm considering the home page domain.com will be redirected to www.domain.com . If you want your page domain.com/forum/view.jsp?thread=124 will be redirect to www.domain.com/forum/view.jsp?thread=124 then you must add this code to every page. Simple idea is make checkURL.jsp and paste the code in this page and include checkURL.jsp in every page.
    StringBuffer requestURL = request.getRequestURL();
    if (request.getQueryString() != null) {
         requestURL.append("?").append(request.getQueryString());
    }
    String completeURL = requestURL.toString();

    if (completeURL.indexOf("www")<0 || completeURL.indexOf("www")>10) {
        String referer = completeURL.substring(referer.indexOf("//") + 2, referer.length());
        referer = "http://www." + referer;
        response.sendRedirect(referer);
    } 
Now when user comes to the page it'll check the URL and if there is not www in URL it'll append and redirect it to desired page.

0 comments :