Java JSP-如何首先转发到视图,然后在后台继续处理该方法?
我想先转到视图“/WEB-INF/views/searchResult.jsp”,然后在后台处理Calculator.lookUp(Type,Place) 当前先处理Calculator.lookUp(Type,Place),只有在该方法完成后,用户才会转发到“/WEB-INF/views/searchResult.jsp”。 谢谢你的帮助Java JSP-如何首先转发到视图,然后在后台继续处理该方法?,java,jsp,servlets,Java,Jsp,Servlets,我想先转到视图“/WEB-INF/views/searchResult.jsp”,然后在后台处理Calculator.lookUp(Type,Place) 当前先处理Calculator.lookUp(Type,Place),只有在该方法完成后,用户才会转发到“/WEB-INF/views/searchResult.jsp”。 谢谢你的帮助 @WebServlet(urlPatterns="/search.do") public class SrchServlet extends HttpSer
@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);
}
}
尝试使用以下代码使方法异步,但类型和位置(仅点变量名称应以小写字母开头)两个变量应为最终变量:
Runnable task = new Runnable() {
@Override
public void run() {
try {
Calculator.lookUp(Type, Place);// here Place and Type both variable should be final
} catch (Exception ex) {
// handle error which cannot be thrown back
}
}
};
new Thread(task, "ServiceThread").start();
到目前为止,我知道下面是解决您问题的更好方法
- 通过将方法声明为
记住,异步方法不会返回任何表示返回类型为void的内容。如果需要返回一些值,可以返回Future。阅读有关进程的更多信息。如果您不喜欢异步请求,请给出一些备注。首先,转发是确定的:您将手交给另一个servlet,下一条指令(如果有的话)将永远不会执行。如果要按顺序进行,则需要包含JSP。还有一个技巧可以使响应立即发送到客户端,同时允许在servlet中进行处理:只需关闭响应输出编写器或流 您的代码可以简单地变成:
//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);
}
我无法确定这是否是每个servlet规范明确允许的,因为我可以确认Tomcat支持它
无需任何
@Asinc
..您可以通过异步请求实现所需的结果。请阅读“谢谢”,这很有道理,但我不知道如何为上述代码设置异步请求。