gpt4 book ai didi

java - 在按下提交按钮后调用 Servlet 中的 Javascript 函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:50:00 25 4
gpt4 key购买 nike

我有一个问题。我知道如何在 servlet 中执行 JavaScript,但是当我想在将用户重定向到另一侧后立即执行它时遇到了问题。所以这是代码,它显示了我的问题。我在 html 端使用提交按钮。

PrintWriter out = response.getWriter();  
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('the session did time out, please reconnect');");
out.println("logout();");
out.println("</script>");
request.getRequestDispatcher("/Login.jsp").forward(request, response);

现在发生的是,我将被重定向到我的登录页面,但我没有看到任何警报。但是当我删除转发行时,会写

PrintWriter out = response.getWriter();  
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('the session did time out, please reconnect');");
out.println("logout();");
out.println("</script>");
// the redirect is missing now

所以现在我收到了警告消息,但我被重定向到一个空白页面,因为根本没有重定向。

所以现在我正在尝试创建一个警报,它会在警报中告诉用户一些事情。紧接着,我想将他重定向到登录页面,我想在其中调用我编写的“注销”功能。

但我既没有收到警报,也没有调用注销功能。基于this质疑这应该有效

最佳答案

what happens now is, i will be redirected to my login page, but i do not see any alert. 

Take a look at the javadoc for RequestDispatcher#forward().

forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.

So when you forward() , the current response is not committed to client and hence your html and javascript code don't run. Forward means your current Servlet is not handling the request, the forwarded code should handle it instead and hence you don't see anything written in the out.println() inside current Servlet as part of final response. Tjis is forwarding the request and is done in the Server side itself, this is not redirection which is initiated by the browser . To redirect you need to use HttpServletResponse#sendRedirect.

So now i am getting the alert message, but i am getting redirected to ablank page

You are not getting redirected to any page , examine closely what you have written to the response :

out.println("<script type=\"text/javascript\">");  
out.println("alert('the session did time out, please reconnect');");
out.println("logout();");
out.println("</script>");

在这种情况下,浏览器会收到类似这样的 HTML 代码:

<html>    
<script type="text/javascript">
alert('the session did time out, please reconnect');
logout();
</script>

此代码将只显示一个警报并调用 logout() 函数(如果有的话)。它显示的 HTML 页面在其当前形式中没有任何可视内容。

关于java - 在按下提交按钮后调用 Servlet 中的 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16478748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com