Edit: This is not a duplicate of this question because I'm trying to send data between doGet
and doPost
of the same servlet. The other question asks about how to send data between different servlets but I'm already doing that by appending the info to the URL (see very first code snippet below), which I can't do within the same servlet. Plus, the linked question is from 2011 and uses Tomcat 5.5, while I'm using 8.5.
I'm working on a small Java 8/Tomcat 8.5 "app" with two servlets and a filter: If the servlet path is "/hello", the filter kicks in and does this if there's no active session:
response.sendRedirect(request.getContextPath() + "/login?p="+request.getServletPath());
This loads the "/login" servlet (LoginServlet.java
) and its html file (LoginHTML.html
):
<body>
<form method="POST" action="login">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="hidden" id="redirect" value="">
<input type="submit" value="Login">
</form>
</body>
Clicking the "Login" button should then load the page that the user tried to access before (via LoginServlet.doPost
), in my case "/hello" (but it could also be "/hello/bla" or "/hello/thisisatest" - even though those don't exist yet).
LoginServlet.doGet
:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String redi = request.getParameter("p");
RequestDispatcher dispatcher = request.getRequestDispatcher("/html/LoginHTML.html");
dispatcher.forward(request, response);
}
redi
contains the path that was accessed before but I'm now looking for a way to somehow pass this to doPost
, so it can go back to the previous page.
As you can see in the above html code, I already added the hidden attribute redirect
to the form but how do I set its value to the value in redi
at runtime (probably in doGet
), so I can access it in doPost
with request.getParameter("redirect")
? Is there another way to do this?