Home > Mobile >  How to set www before domain name and after http:// in Spring Boot and JavaScript?
How to set www before domain name and after http:// in Spring Boot and JavaScript?

Time:12-01

I want to know about redirection of domain. That is I want to add www before domain name. How to achieve this thing in Spring boot and JavaScript.

My URL is : https://example.com/dashboard

I want this: https://www.example.com/dashboard

CodePudding user response:

I think it should be configured in the frontend like apache or proxy (nginx or other).

CodePudding user response:

I would advise to redirect at your web server configuration, outside the Spring Boot aplication. But in case you want to redirect for some specific reason you could add Filter to your Spring Boot Configuration:

@Component
public class RedirectionFilter extends GenericFilterBean {

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

        final String host = request.getServerName();
    
        if (!org.apache.commons.lang.StringUtils.startsWithIgnoreCase(host, "www.")) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            
            //obtain the full requested URL
            StringBuffer requestURL = httpRequest.getRequestURL();
            String queryString = httpRequest.getQueryString();
            if (queryString != null) {
                requestURL.append("?").append(queryString);
            }
            
            //set up redirect
            String redirectURL = requestURL.toString();
            redirectURL = redirectURL.replace(host, "www."   host);
            httpResponse.sendRedirect(redirectURL);
        }  else {
            chain.doFilter(request, response);
        }
    }
}
  • Related