I need to display the data from a servlet in a jsp page. At the moment I have this:
SERVLET:
Object data = text;
request.setAttribute("data", data);
request.getRequestDispatcher("index.jsp").forward(request, response);
JSP:
<p>result: ${data}</p>
In the JSP there is a simple text box and a send button. At the moment when I push the send button the response is being overwritten ervery time.
How can I do it that after every search I see the result in a new line? I want also see the previous searches...
Thanks a lot!
You've got a couple of options:
Send over the current value to the server, do the search and append the new result there, and send back the whole string to the JSP in the Request
to display it all again. You'll have to wrap the value in an <input>
tag, possibly <input type="hidden">
if you still want to show data
in a <p>
and not as an input field.
JSP:
<input type="hidden" name="oldData" value="${data}"/> <p>result: ${data}</p>
Servlet:
Object newData = text; Object oldData = request.getParameter("oldData"); request.setAttribute("data", oldData + "<br/>" + newData); request.getRequestDispatcher("index.jsp").forward(request, response);
Store all values of data
in the session scope, and just append to it from your servlet. The JSP would have to output the value from the session scope instead of the request. In this example values are stored in a unique concatenated String
. It woukld probably be nicer to store each value of data
in a data structure, such as a List
, and just iterate over it in the JSP so the separator remains in the view.
JSP:
<c:if test="${not empty sessionScope.data}"> <p>result: ${sessionScope.data}</p> </c:if>
Servlet:
Object newData = text; Object oldData = request.getSession().getAttribute("data"); request.getSession().setAttribute("data", oldData + "<br/>" + newData); request.getRequestDispatcher("index.jsp").forward(request, response);
1 .Use an array instead of a simple object in servlet
Populate the array with the new values :Servlet
Traverse the array and display each item where ever you want to display as new lines
You are putting your data in RequestScope
you have to add them into the SessionScope
in order to see the previous results.
See this example: http://viralpatel.net/blogs/jsp-servlet-session-listener-tutorial-example-in-eclipse-tomcat/ .
It is not very good practice to write java code in JSP
, so you would want to move the logic into servlet. But this example describes the point you need.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.