【问题标题】:Redirect JSP from JSP - error "The requested resource is not available." [duplicate]从 JSP 重定向 JSP - 错误“请求的资源不可用。” [复制]
【发布时间】:2015-03-16 12:40:09
【问题描述】:

我正在开发一个社交网站,但遇到以下问题。在profile.jsp 我有一个表单,用户可以在其中上传照片。这个表单对FileUploadHandler servlet 有一个动作,它上传照片然后将重定向发送到uploadfileController.jsp,如下所示:

RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/uploadfileController.jsp");
requestDispatcher.forward(request, response);

uploadfileController.jsp 中,我将此帖子插入到我的 MySQL 数据库中,并将重定向发送到profile.jsp

response.sendRedirect("/profile.jsp");

但随后我收到此错误消息:

HTTP 状态 404 - /profile.jsp

输入状态报告

消息/profile.jsp

说明请求的资源不可用。

但是,当我再次访问profile.jsp 时,帖子已创建!有什么想法吗?

【问题讨论】:

  • profile.jsp 的完整 URL 是什么样的?是不是类似于http://server/webAppName/profile.jsp
  • 是的,一模一样

标签: java jsp servlets


【解决方案1】:

您可以将sendRedirect 与相对地址一起使用。例如,如果 servlet URL 是

http://www.serwer.com/yourwebapp/foo/servlet

您将使用sendRedirect("bar/other"),您将被重定向到同一上下文中的不同资源

http://www.serwer.com/yourwebapp/foo/酒吧/其他

但是如果您在sendRedirect 的开头添加/,那么/ 将代表您服务器的主目录,

http://www.serwer.com/
                     ^this one

所以sendRedirect("/bar/other") 会将您重定向到

http://www.serwer.com/酒吧/其他

如您所见,yourwebappfoo 已从 URL 中删除。

在您的情况下,问题似乎是缺少yourwebapp。您可以通过多种方式解决它。例如,您可以:

  • 从重定向位置的开头删除 / 以使其相对于当前 URL
  • / 之后添加应用程序名称,例如sendRedirect("/yourAppName/profile.jsp")(您可以通过将request.getContextPath() 用作request.getContextPath() 动态获取/yourAppName 作为mentioned by Roman C +1 以获取他的信息)

【讨论】:

  • 非常感谢,我很困惑,你帮了很多忙!! :)
  • @KonstantinaPapagiannopoulou 欢迎您。在创建重定向时丢失应用程序名称是我们在 Web 开发中面临的标准问题之一 :)
  • @KonstantinaPapagiannopoulou 如果他帮了很多忙,你应该支持他的回答;)
【解决方案2】:

如果响应与 servlet 上下文相关,则将上下文路径添加到 URL。

String contextPath = request.getContextPath();
response.sendRedirect(response.encodeRedirectURL(contextPath + "/profile.jsp"); 

【讨论】:

  • 成功了,谢谢!! :)
猜你喜欢
  • 1970-01-01
  • 2013-01-06
  • 2015-12-09
  • 2016-09-21
  • 1970-01-01
  • 2016-02-15
  • 2015-11-23
  • 2016-03-14
  • 1970-01-01
相关资源
最近更新 更多