我有一个调用servlet的jsp。这个servlet执行一些任务,然后我想返回到我刚刚访问的页面并重新加载它。如果我知道每次使用redirectUrl时的确切URL,这将很简单。但是,我无法在其中硬编码,因为它是动态创建的。当前一个网址不为我所知时,有没有办法做到这一点?
答案 0 :(得分:0)
我不确定我是否理解正确,您是否需要从jsp移动到servlet,并返回相同的jsp?如果这是你需要的,我会把一些隐藏的输入放在带有路径
的jsp表单中<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
完整的解决方案如下:
的Page1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
${requestScope.dataFromServlet }
<form action="${pageContext.request.contextPath}/HelloWorldServlet " method="POST">
<input type="hidden" name="jspPath" value="${pageContext.request.requestURI}"/>
<input type="hidden" name="param1" value="value1"/>
<input type="submit" value="Submit">
</form>
</body>
</html>
HelloWorldServlet.java
public class HelloWorldServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String jspPath = request.getParameter("jspPath");
if(jspPath == null || "".equals(jspPath))
jspPath = "errorPage.jsp";
request.setAttribute("dataFromServlet", "Hello World");
RequestDispatcher rd = request.getRequestDispatcher(jspPath);
rd.forward(request, response);
}
}