13

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 the page(path) from which I was redirected to use it in next servlet command(to go to previous page). How could I get it? Or previous URL is not contained in request parameters and I should add it myself? Will be very grateful for your help.

And
  • 343
  • 1
  • 5
  • 15

4 Answers4

21

String referer = request.getHeader("Referer"); response.sendRedirect(referer);

SEE: Link to forum answer

Gyan
  • 1,176
  • 1
  • 12
  • 26
14

Try using

request.getAttribute("javax.servlet.forward.request_uri")  

See
https://tomcat.apache.org/tomcat-9.0-doc/servletapi/constant-values.html
and
How to get the url of the client

rickz
  • 4,324
  • 2
  • 19
  • 30
1

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:

...
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>my.package.CustomFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>*</url-pattern>
</filter-mapping>
...

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();
jlbofh
  • 433
  • 5
  • 7
-1

you can store that url in HttpSession and retrieve it in next servlet when you need.

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58