How to access static resources when mapping a global front controller servlet on /*

前端 未结 19 2355
轮回少年
轮回少年 2020-11-22 07:35

I\'ve mapped the Spring MVC dispatcher as a global front controller servlet on /*.

               


        
19条回答
  •  没有蜡笔的小新
    2020-11-22 07:59

    Map the controller servlet on a more specific url-pattern like /pages/*, put the static content in a specific folder like /static and create a Filter listening on /* which transparently continues the chain for any static content and dispatches requests to the controller servlet for other content.

    In a nutshell:

    
        filter
        com.example.Filter
    
    
        filter
        /*
    
    
    
        controller
        com.example.Controller
    
    
        controller
        /pages/*
    
    

    with the following in filter's doFilter():

    HttpServletRequest req = (HttpServletRequest) request;
    String path = req.getRequestURI().substring(req.getContextPath().length());
    
    if (path.startsWith("/static")) {
        chain.doFilter(request, response); // Goes to default servlet.
    } else {
        request.getRequestDispatcher("/pages" + path).forward(request, response);
    }
    

    No, this does not end up with /pages in browser address bar. It's fully transparent. You can if necessary make "/static" and/or "/pages" an init-param of the filter.

提交回复
热议问题