java 返回到在 Servlet 中使用 RequestDispatcher 发送请求的同一个 JSP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17317578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Go back to same JSP that sent request with RequestDispatcher in Servlet
提问by Colinch
I have a servlet which can get requests by multiple JSP's.
我有一个 servlet,它可以通过多个 JSP 获取请求。
But when I use the RequestDispatcher in the servlet, I don't know how to forward to the JSP that sent the request.
但是当我在servlet中使用RequestDispatcher时,我不知道如何转发到发送请求的JSP。
req.getRequestDispatcher("page.jsp").forward(req, resp);
I know there is something like this in html: javascript:javascript:history.go(-1)
我知道 html 中有这样的东西:javascript:javascript:history.go(-1)
I just need something like this:
我只需要这样的东西:
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(originalRequest).forward(req, resp);
That piece of code is probably very noob but it gives you the idea of what I need.
这段代码可能非常菜鸟,但它让您知道我需要什么。
So: I need to forward to the page that sent the original request (basically reload the page), but because multiple jsp's use the servlet, I cannot simply forward to "page.jsp"
所以:我需要转发到发送原始请求的页面(基本上重新加载页面),但是因为多个jsp使用servlet,我不能简单地转发到“page.jsp”
回答by Prasad Kharkar
You can do following
您可以执行以下操作
- Create a hidden parameter for every jsp named
jspName
and give value for respective JSPs. e.g. for JSP A, parameter name isjspName
and value isa
, for JSP B, parameter name isjspName
and value isb
Read this hidden parameter in the servlet using following code.
String jspName = request.getParameter("jspName"); RequestDispatcher rd = request.getRequestDispatcher(jspName); rd.forward(request, response);
- 为每个命名的 jsp 创建一个隐藏参数,
jspName
并为相应的 JSP 提供值。例如对于 JSP A,参数名称是jspName
,值是a
,对于 JSP B,参数名称是jspName
,值是b
使用以下代码读取 servlet 中的这个隐藏参数。
String jspName = request.getParameter("jspName"); RequestDispatcher rd = request.getRequestDispatcher(jspName); rd.forward(request, response);
When you are calling the servlet from JSP A, then it will have paramter japName=a
, when servlet code is running, it will retrieve the value a
from request.getParamter("jspName")
and a getRequestDispatcher(jspName)
will create the dispatcher for the same and rd.forward(request, response)
will forward to the jsp.
当您从 JSP A 调用 servlet 时,它将具有 paramter japName=a
,当 servlet 代码运行时,它将a
从中检索值request.getParamter("jspName")
,agetRequestDispatcher(jspName)
将为其创建调度程序rd.forward(request, response)
并将转发到 jsp。
回答by SM ANSARI
I have not tried the following, but I hope this may help you to solve your problem.
我还没有尝试过以下方法,但我希望这可以帮助您解决问题。
req.setAttribute("originalRequest", req.getRequestPage());
req.getRequestDispatcher(req.getAttribute(originalRequest).toString()).forward(req, resp);