2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

How to handle only www url redirect to my domain

Problem is while user enters the domain name for example example.com my application open in browser. But i need to make sure like if user enters example.com it will automatically navigate or redirect to www.example.com. Web application developed in java and spring. How to handle it using server or using java code?

userimage

Try below code and configure below interceptor to make sure URL will redirect to www.example.com

package com.test;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class RedirectToWWW extends HandlerInterceptorAdapter {

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
         throws InvalidUrlException {
      if (!request.getRequestURL().toString().toLowerCase().startsWith("http://www.")) {
         String url = request.getRequestURL().toString().replace("http://", "http://www.");
         try {
            response.sendRedirect(url);
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return true;
   }
}
Answer is