Display form-processing results on current page in JSP

淺唱寂寞╮ 提交于 2020-01-06 05:47:25

问题


Currently I'm able to send some form data from an HTML page to a Servlet, process it, and return the result by forwarding/redirecting to a displayresults.jsp page; However I'm wondering if there's a way to process a form submission in this fashion and then return the results to the initial page? So that whatever I wish to return shows up below the form.

The idea in the end will be to have a search function up top, then have the search results appear below on the same page.


回答1:


Yes

  1. Stick the results into the request object from within the servlet
  2. Get the servlet to forward back to the request page
  3. Add some code into the JSP to pull out the results from the request object and display them

See this for a simple example http://www.tek-tips.com/viewthread.cfm?qid=1189624&page=11

If your usecase means that you'll be jumping from the search results elsewhere and back you may wish to maintain the search results in the session.




回答2:


<c:choose>
<c:when test="${empty param.search}">
    <form method="post"><input type="text" name="search" /></form>
</c:when>
<c:otherwise>
    <%-- show search result here. --%>
</c:otherwise>
</c:choose>



回答3:


Personally, I almost always put my "collect search criteria" and "display results" in the same servlet or JSP file. I write them with this basic structure:

if request data is present
  collect search criteria from request object
  check for errors
else // i.e. first time in
  fill search criteria with blanks or defaults
end if

display error messages // if any, of course
display search criteria // either what we got from last cycle or defaults

if request data was present
  process request
  display results
end if

I like this structure because on an error, I'm set up to display the bad data, let the user fix just what was wrong, and then cycle back through. On success, I'm set to let him adjust the criteria and re-run. Everything is in one place but it's structured so it's not a mess.

When it's up to me I rarely use servlets: I prefer to use JSP for the top level and put the non-trivial, non-display code in other classes that I simply call, but that's an implementation detail. The principle works as well with servlets as with JSP.



来源:https://stackoverflow.com/questions/1228571/display-form-processing-results-on-current-page-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!