Double forward in one servlet

时光总嘲笑我的痴心妄想 提交于 2019-12-02 15:01:14

问题


I have one JSP page that have a form. When the button in this form is pushed, id called my MainServlet. This is an example of my Servlet

/***** MainServlet *****/    

/* Call the servlet that comunicate with database */  
request.getRequestDispatcher("Servlet1").forward(request,response)

/* Return on the same JSP that have invoke MainServlet */
request.getRequestDispatcher("myJsp.jsp").forward(request,response);

return;

This is wrong because when I push the button in the form, my server return an error: "Cannot forward after response has been committed"

How can I solve this problem?

Thanks.


回答1:


You cannot forward to two different resources at the same time.

You need to again forward from Servlet1 to myJsp.jsp using request.getRequestDispatcher("myJsp.jsp").forward(request,response);

You cannot just directly forward two times because when you do it once, your response is already committed and client will be served with the first resource.

You can use conditional statements which will forward to proper resource depending on the proper request.




回答2:


Once a request has been forward, the remaining codes are not executed. Its same like calling a return statement twice one after another in a method. If you want both forwards to work. You should use conditions, depending upon which, one of the forward statement will be executed.



来源:https://stackoverflow.com/questions/19156250/double-forward-in-one-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!