使用 java servlet 将数据从一个 html 页面传递到另一个页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14953143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:59:56  来源:igfitidea点击:

Passing data from one html page to another with java servlets

javahtmlservletspostweb

提问by user1782677

So I have one html form in "File1.html"

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

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

Then in my servlet I do the following:

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

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

So after the user hits the "submit" button in File1, the servlet takes the user to File2. But how do I access the data that was inputed in the first file in the second file?

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

回答by Hussain Akhtar Wahid 'Ghouri'

before using the Dispatcher set the attribute you want to pass

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

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

in your case

在你的情况下

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

and on the dispached page , get it by

并在调度页面上,通过

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

回答by SudoRahul

You can get it this way:-

你可以通过这种方式得到它:-

request.getParameter("param");

request.getParameter("param");

回答by Jason

You can put parameter to request:

您可以将参数放入请求:

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

and you can get data from new servlet or jsp like :

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

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

回答by foxty

If you redirect to a static html file, you can not get the parameter or attribute via servlet.

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

If you don't have any business in the servlet, you can just use , then get the data from File2.html via javascript.

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



Or you can redirect to the File2.html in your servlet and attach the data by query string like "File2.html?name=blablabla" and use javascript in File2.html to get these data.

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

btw, in javascript you can use window.location.href to get current url which include the query string.

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