在找到此解决方案后,我以为我已经解决了我之前发布的一个问题:Javascript Post on Form Submit open a new window。但是,它并不能完全满足我的要求,而且我无法弄清楚缺少什么。
这是问题所在...我有一个带有表单的jsp。提交表单时(通过 JavaScript),我希望父窗口始终重定向到另一个页面。但是,根据用户的输入值,我也有条件地想要打开另一个窗口并将那个窗口重定向到不同的页面。因此,始终重定向父级,有时打开并重定向子级。
我在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>
这是html表单:
<form id='myForm' method='post' action='someAction' accept-charset='UTF-8'>
// some hidden input elements here
</form>
和 servlet 逻辑:
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);
}
}
当条件不满足时,一切正常。servlet 被调用,调用页面被重定向到 parentPage。但是,如果满足条件,则 servlet 会在新的子窗口中正确打开 childpage.jsp,但不会将调用方页面重定向到 parentPage。
我尝试添加显式重定向(“parentPage.jsp”);在form.submit() 之后;,但这会产生竞争条件并且不是一个好的解决方案,因为在提交表单后不应调用任何内容。
我还尝试修改 servlet 内部的逻辑,并且仅在检测到条件时才重定向。但是,当条件不存在时,这会导致问题,因为 servlet 不知道接下来将用户发送到哪里。
有没有办法让我将多个表单传递给一个 servlet 并通过 Java 处理它?任何帮助将不胜感激。
-鲍勃