Dienstag, 28. Januar 2014

Solve relative image paths in css used in a JSP file.

I need to use a CSS template for a new project. All background images has been defined in CSS files as relative paths like :

background-image: url('../../images/logo.png');

It was fine if i call an URL : http://www.mydomain.com/console

But i call http://www.mydomain.com/console/create/company , browser can not find the images because it will search this relative path on console/images which does not exist.

I don't want to touch the developer source code and need to find a generic solution. Because if i change the base path. it must also work perfect.

My solution was easy, redirect to an absolute URL depends on context etc. Therefore i wrote a filter to redirect assets into their real paths. Let see in action :)
public class ResourceFilter implements javax.servlet.Filter {

    private static final String ASSETS_FOLDERS = "assets";

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        if (req instanceof HttpServletRequest) {
            HttpServletRequest servletRequest = (HttpServletRequest) req;

            String uri = servletRequest.getRequestURI();
            if (uri.contains(ASSETS_FOLDERS)) {

                HttpServletResponse httpResponse = (HttpServletResponse) resp;

                String replaced = uri.substring(uri.lastIndexOf(ASSETS_FOLDERS), uri.length());
                String toRedirect =  servletRequest.getContextPath() + "/" + replaced;

                if (toRedirect.equals(uri)) { // If absolute redirect path equals to uri don't redirect it again. Prevent cycles.
                    chain.doFilter(req, resp);
                    return;
                }
                
                httpResponse.sendRedirect(toRedirect);
                return;
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {}

    public void destroy() {}
}

Keine Kommentare:

Kommentar veröffentlichen