tags:

views:

774

answers:

3

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  A: 

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.

pjp
Ahh ok, this really is one of those times where the answer seemed too simple to be true. Thanks a lot
Jeff Dalley
+2  A: 
<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>
Mohammad Alinia
I like the standard c tag it makes things nice and clear. The example in the link I posted was using scriptlets which are so 90's.
pjp
That's right, scriptlets are so messy!
Mohammad Alinia
+1  A: 

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.

Jay