3

Initially there was a "sign out" link only on my index page, so I would just invalidate the session and send it back to index page....

But now I have a "sign out" link on the top of every page. So how could I dispatch a request back to the same page from where the "sign out" was clicked after invalidating a session?

HttpSession hs = request.getSession();
if (hs != null) {
    hs.invalidate();
    RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
    rd.forward(request, response);
}
informatik01
  • 16,038
  • 10
  • 74
  • 104
user153834
  • 53
  • 1
  • 4
  • You can send a `request` attribute to the index page and on login use that attribute to redirect to the current page in the login handler. You can keep that request attribute as a hidden field etc. – AllTooSir May 25 '13 at 18:42
  • Possible duplicate / similar to this: [HttpServletRequest - how to obtain the referring URL?](http://stackoverflow.com/questions/2648984/httpservletrequest-how-to-obtain-the-referring-url) and this: [how to use request.getHeader(“Referer”)](http://stackoverflow.com/questions/5536577/how-to-use-request-getheaderreferer) – informatik01 May 25 '13 at 21:56

2 Answers2

1

Use HttpServletRequest#getHeader() to retrieve the HTTP referrer.

HttpSession session = request.getSession();
if(session !=null) {
    session.invalidate();
    RequestDispatcher rd;
    String referrer = request.getHeader("Referer");
    if (referrer != null) {
        URL ref = new URL(referrer);
        // assuming logout request came from the same application
        referrer = ref.getPath().substring(request.getContextPath().length());
        rd = request.getRequestDispatcher(referrer);
    } else {
        rd = request.getRequestDispatcher("/index.jsp");
    }
    rd.forward(request, response);
}

substring() was done to remove the context root of the application because the dispatcher would also be adding the same. Without removing it the resulting path would become invalid (with two contexts /webapp/webapp/.. in the front).

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

you can store a session attribute for the previous page and current servletContext. whenever there is a new request, get current servletContext from session and set it as previous context and then replace current servletContext with the servletContext of the new request. Now any time you want to send user to previous view, get the previous view from session and use response.sendRedirect((String)session.getAttribute("previousPath")). works great for me.

qualebs
  • 1,291
  • 2
  • 17
  • 34