如何重定向到 html 页面并将变量传递给 Java 中的该页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/646247/
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
How do I redirect to a html page and pass variables to that page in Java?
提问by Abs
I have a form on my index.html page which makes a POST request to a Java Servlet. This servlet does some processing and I would like to redirect back to index.html with some variables that the servlet has produced.
我的 index.html 页面上有一个表单,它向 Java Servlet 发出 POST 请求。这个 servlet 做了一些处理,我想用 servlet 产生的一些变量重定向回 index.html。
In PHP, it would be as simple as:
在 PHP 中,它会很简单:
header("Location: index.html?var1=a&var2=b");
How can I acheive the same with Java, hopefully making use of a GET request.
我怎样才能用 Java 达到同样的效果,希望能利用 GET 请求。
Thanks all
谢谢大家
采纳答案by Eric Wendelin
In a Java Servlet, you'll want to write:
在 Java Servlet 中,您需要编写:
response.sendRedirect("index.html?var1=a&var2=b...");
Oh right, I should note that you'll want to do this in the processor method like doGet() or doPost()...
哦对了,我应该注意到你会想在像 doGet() 或 doPost() 这样的处理器方法中这样做......
回答by Tommy Hui
回答by Mork0075
You redirect the response to the same servlet with some additional values:
您使用一些附加值将响应重定向到同一个 servlet:
req.setAttribute("message","Hello world");
rd =req.getRequestDispatcher("/index.jsp");
And in your servlet, you grab the data with:
在您的 servlet 中,您可以通过以下方式获取数据:
<%=request.getAttribute("message");%>
回答by WiseTechi
It is as simple as :
它很简单:
response.sendRedirect("index.html?var1=a&var2=b");