If you're using container managed authentication, then this is not possible. It will only be automatically handled whenever the query string is actually in that restricted URL for which the enduser is been presented the login page first. The container would after a successful login automatically redirect back to the restricted URL, complete with the original query string.
If you're using homegrown authentication, then you just need to copy the current query string in the login URL. E.g.
<form action="login?${pageContext.request.queryString}" method="post">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" value="login" />
</form>
Then, in the servlet's doPost()
, or wherever you're handling the login, then just grab the query string by HttpServletRequest.getQueryString()
and pass it through on redirect. E.g.
User user = userService.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Do whatever you need to represent a logged-in user.
response.sendRedirect(request.getContextPath() + "/index.jsp?" + request.getQueryString());
}
else {
// Show "unknown login" error?
}
All with all, I'm not sure how this functional requirement of having the query string in the login URL makes sense in real world. It would make more sense if that query string was part of the original restricted URL for which you'd need to login first, exactly as the standard container managed authentication mechanism supports. So perhaps you need to rethink the one and other again.