gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:52:52 25 4
gpt4 key购买 nike

我想先转发到 View “/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);

}
}

最佳答案

如果您不喜欢异步请求,请备注一些。首先,转发是确定的:您将手交给另一个 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...

关于java - JSP - 如何首先转发到 View ,然后在后台继续处理方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47771584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com