Issue
I would like to first forward to the view "/WEB-INF/views/searchResult.jsp" and then process Calculator.lookUp(Type, Place) in the background.
Currently Calculator.lookUp(Type, Place) is processed first, and only once this method is finished is the user forwarded to "/WEB-INF/views/searchResult.jsp". Thanks for the help!
@WebServlet(urlPatterns="/search.do")
public class SrchServlet extends HttpServlet{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String Type = request.getParameter("Type");
String Place = request.getParameter("Place");
request.setAttribute("Type", Type);
request.setAttribute("Place", Place);
//I want the forward to searchResult.jsp to occur
request.getRequestDispatcher("/WEB-INF/views/searchResult.jsp").forward(
request, response);
//and then in backend for the below method to run
Calculator.lookUp(Type, Place);
}
}
Solution
Some remarks if you do not like async requests. First, a forward is definitive: you give the hand to the other servlet and next instruction (if any) will never be executed. You need to include the JSP if you want to proceed in sequence. And a trick allows to cause the response to be sent to the client immediately while allowing processing in the servlet: just close the response output writer or stream.
Your code could simply become:
//I want the include searchResult.jsp
request.getRequestDispatcher("/WEB-INF/views/searchResult.jsp").include(
request, response);
// cause the response to be sent to the client
try {
response.getOutputStream().close(); // if the OutputStream was used
}
catch(IllegalStateException e) {
response.getWriter().close(); // if the Writer was used
}
//and then in backend for the below method to run
Calculator.lookUp(Type, Place);
}
I could never find whether this was explicitely allowed per servlet specification, by I can confirm that Tomcat supports it.
No need for any @Asinc
...
Answered By - Serge Ballesta