I thought I had resolved a question I posted earlier after finding this solution: Javascript Post on Form Submit open a new window. However, it doesn't quite do what I want and I can't figure out what's missing.
Here's the issue... I have a jsp with a form in it. When the form is submitted (via JavaScript) I want the parent window to ALWAYS redirect to another page. However, depending on the user's input values, I also CONDITIONALLY want to open another window and redirect THAT window to a different page. So, always redirect parent, sometimes open and redirect child.
My code in the jsp:
<script>
function handleFormSubmit() {
var form = document.getElementById("myForm");
...
if (checkbox.checked) {
// this code creates the child window, but ONLY if the checkbox is checked
myForm.setAttribute("target", "newResultPage");
window.open("childpage.jsp", "newResultPage", "width=850,height=550,...");
}
form.submit();
}
</script>
And here's the html form:
<form id='myForm' method='post' action='someAction' accept-charset='UTF-8'>
// some hidden input elements here
</form>
And the servlet logic:
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String redirectedPage = "/parentPage";
if (someCondition) {
redirectedPage = "/childpage.jsp";
}
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher(redirectedPage);
reqDispatcher.forward(request,response);
}
}
When the condition is not met, everything works fine. The servlet is invoked and the calling page is redirected to parentPage. However, if the condition IS met, the servlet correctly opens childpage.jsp in a new child window, but it does NOT redirect the caller page to parentPage.
I've tried adding an explicit redirect("parentPage.jsp"); after form.submit();, but that creates a race condition and is not a good solution since nothing should be called after the form is submitted.
I've also tried modifying the logic inside the servlet, and only redirecting if the condition is detected. However, this causes an issue when the condition isnt' present, since the servlet doesn't know where to send the user next.
Is there a way for me to pass multiple forms to a servlet and handle it via Java? Any help would be greatly appreciated.
-Bob