【问题标题】:Passing data from one html page to another with java servlets使用 java servlet 将数据从一个 html 页面传递到另一个页面
【发布时间】:2013-02-03 21:03:57
【问题描述】:

所以我在“File1.html”中有一个 html 表单

<form action="MyServlet" method="post">
    MyData: <input type="text" name="data"><br>
    <input type="submit" value="submit">
</form>

然后在我的 servlet 中执行以下操作:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher myDispatch = request.getRequestDispatcher("File2.html");
    myDispatch.forward(request, response);
    }

因此,当用户点击 File1 中的“提交”按钮后,servlet 会将用户带到 File2。但是如何在第二个文件中访问第一个文件中输入的数据呢?

【问题讨论】:

    标签: java html servlets post web


    【解决方案1】:

    你可以这样得到它:-

    request.getParameter("param");

    【讨论】:

    • 酷,所以我要从 html 文件中调用这个函数吗?还是来自servlet?如果我从 servlet 调用它,我仍然需要以某种方式将它传递到 html 文件中,对吗?
    【解决方案2】:

    您可以将参数放入请求中:

    String data = request.getParameter("data");
    request.setAttribute("key",data);
    myDispatch.forward(request, response);
    

    您可以从新的 servlet 或 jsp 中获取数据,例如:

    Object data = request.getAttribute("key");
    

    【讨论】:

      【解决方案3】:

      在使用 Dispatcher 之前设置你要传递的属性

      request.setAttribute("AttributeName","This is the Attribute value.");
      

      你的情况

      request.setAttribute("data",request.getParameter("data"));
      

      在发送的页面上,通过

      获取
      String something =  request.getAttribute("data");
      

      【讨论】:

      • 谢谢!还有一个问题,在 HTML 中调用 String something = "..." 是否合法?还是我需要使用 Javascript?我问是因为最终我想在

        中显示数据
      • 那我不明白你在哪里写的“在发送的页面上,通过...获取它”。发送的页面是我的 html 文件。我打算使用 html 文件中的数据并将其显示到屏幕上。
      • 请求调度器应该调用另一个servlet或jsp页面,在那里你可以调用它,请求对象不能传递给HTML页面。你可以把你的JSP页面当作你的HTML页面
      【解决方案4】:

      如果重定向到静态html文件,则无法通过servlet获取参数或属性。

      如果你在servlet中没有任何业务,你可以直接使用,然后通过javascript从File2.html中获取数据。


      或者您可以重定向到您的 servlet 中的 File2.html,并通过“File2.html?name=blablabla”之类的查询字符串附加数据,并在 File2.html 中使用 javascript 来获取这些数据。

      顺便说一句,在 javascript 中,您可以使用 window.location.href 来获取包含查询字符串的当前 url。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 2020-11-20
        • 1970-01-01
        • 2012-01-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多