經過Filter攔截指定url的請求後更改url進行轉發

攔截/web開頭的請求,而後把url中的/web去掉進行轉發

@WebFilter(urlPatterns = "/web/*")
public class WebForwardFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = (HttpServletRequest) request;
            String uri = req.getRequestURI();
            if (uri.startsWith("/web")) {
                String newPath = uri.replace("/web", "");
                RequestDispatcher requestDispatcher = request.getRequestDispatcher(newPath);
                requestDispatcher.forward(request, response);
                return;
            }
        }
        chain.doFilter(request, response);

    }


    @Override
    public void destroy() {
    }
}
相關文章
相關標籤/搜索