2013-02-19 73 views
1

所以我有一个HTML形式“的file1.html”将数据传递到另一个Java servlet为

<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。但是,如何访问第二个文件中第一个文件中输入的数据?

回答

2

在使用分派器之前设置要传递的属性

request.setAttribute("AttributeName","This is the Attribute value."); 
你的情况

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

和dispached页面上

,通过

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

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

user1782677 2013-02-19 09:00:05

+0

都能跟得上这可以在servlet或JSP只能调用 – 2013-02-19 09:06:30

+0

然后,我不明白的地方,你写的“被派遣页面上,通过得到它......”里面的数据。派发的页面是我的html文件。我打算使用html文件中的数据并将其显示在屏幕上。 – user1782677 2013-02-19 09:08:12

0

你可以这样说: -

request.getParameter("param");

+0

很酷,所以我从HTML文件中调用这个函数?还是从servlet?如果我从servlet中调用它,我仍然需要以某种方式将它传递给html文件,对吗? – user1782677 2013-02-19 08:48:07

0

你可以把参数要求:

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

,你可以得到由新的Servlet的数据或JSP喜欢:

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

得到它,如果您重定向到一个静态的html文件,你不能得到的参数或属性通过servlet。

如果你没有在servlet的任何业务,则可以只使用,然后通过JavaScript得到File2.html数据。


或者你可以重定向到File2.html在你的servlet和查询字符串,如“File2.html?NAME = blablabla的”将数据和使用JavaScript在File2.html得到这些数据。

顺便说一句,在JavaScript中,你可以用window.location.href获取当前的URL,其中包括查询字符串。

相关问题