Reputation: 53
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);
}
Upvotes: 3
Views: 2688
Reputation: 1381
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.
Upvotes: 1
Reputation: 51711
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).
Upvotes: 1