kamal
kamal

Reputation: 77

Tomcat, Spring MVC, redirecting users to 'www' without using htaccess file

I am trying to append www. to the domain but I can't find a solution. I found the results using .htaccess file but this solution works with Apache server but I am working with Tomcat.

For eg.
When user types in: abcdomain.com
then it should redirects to the : www.abcdomain.com

Any help would greatly appreciated.

Upvotes: 3

Views: 841

Answers (1)

Jan
Jan

Reputation: 13858

The one thing that comes to mind would be a Filter processing the requests before they hit your app:

public class RedirectFilter implements Filter {

    @Override
    public void destroy() {     
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
            throws IOException, ServletException {
        if(arg0 instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest)arg0;
            String url = req.getRequestURL().toString()+"?"+req.getQueryString();
            Pattern p = Pattern.compile("(?i)(http(s?)://)www\\.");
            Matcher m = p.matcher(url);
            if(m.find()) {
                //www is present -> continue
                chain.doFilter(arg0, arg1);
            } else {
                StringBuilder wwwurl = new StringBuilder();
                if(url.toLowerCase().startsWith("http://")) {
                    wwwurl.append("http://www.").append(url.substring(7));
                } else if(url.toLowerCase().startsWith("https://")) {
                        wwwurl.append("https://www.").append(url.substring(8));
                }                   
                ((HttpServletResponse)arg1).sendRedirect(wwwurl.toString());
            }
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {       
    }
}

Upvotes: 3

Related Questions