JSP - 如何首先转发到视图,然后在后台继续处理方法?

时间:2017-12-12 11:30:36

标签: 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 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);

          }   
}

3 个答案:

答案 0 :(得分:1)

如果您不喜欢异步请求,请注意一些内容。首先,前进是明确的:你将手交给另一个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 ...

答案 1 :(得分:0)

尝试使用下面的代码使你的方法异步,但是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();

答案 2 :(得分:0)

据我所知,以下是解决问题的更好方法。

  • 通过将方法声明为,
  • 声明您需要在异步方法中作为后台进程的一部分执行的逻辑
  

@Asynchronous / @Async

请记住,异步方法不会返回任何意味着返回类型为void的内容。如果需要返回一些值,可以返回Future。详细了解Asynchronous流程。