How to get the previous page URL from request in servlet after dispatcher.forward(request, response)

前端 未结 4 1744
借酒劲吻你
借酒劲吻你 2020-12-17 16:18

I\'m using the servlet which redirects me with the help of

dispatcher.forward(request, response);

in the end. But after this I want to get

4条回答
  •  生来不讨喜
    2020-12-17 16:54

    Any method will return source URL when you do forward(..) so my solution is to define a filter to store the requestURL() in a request attribute to check later. To do this in your web.xml write:

    ...
    
        MyFilter
        my.package.CustomFilter
    
    
        MyFilter
        *
    
    ...
    

    Then in CustomFilter class:

    public class CustomFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}
    
        @Override
        public void destroy() {}
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse rsp,
                FilterChain chain) throws IOException, ServletException {
            req.setAttribute("OriginURL", req.getRequestURL().toString());
            chain.doFilter(req, rsp);
        }
    }
    

    Then you can get it everywhere in your code with ServletRequest object with:

    request.getAttribute("OriginURL").toString();
    

提交回复
热议问题