1

So I have one html form in "File1.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:

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?

4 Answers 4

2

before using the Dispatcher set the attribute you want to pass

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");
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Just one more question though, is it legal to just call String something = "..." in HTML? Or do I need to use Javascript? I ask because eventually I want to display the data inside a <p></p>
Then I don't understand where you wrote "and on the dispatched page, get it by...". The dispatched page is my html file. I plan on using the data inside the html file and displaying it to the screen.
the request dispatcher should call another servlet or jsp page , there you can call it , request object cant be passed to HTML page .you can treat your JSP page like your HTML page
0

You can get it this way:-

request.getParameter("param");

1 Comment

Cool, so do I call this function from within the html file?. Or from the servlet? And if I call it from the servlet, I would still need to pass it into the html file somehow, correct?
0

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 :

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

Comments

0

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

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


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.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.