【问题标题】:Servlet forwardingServlet 转发
【发布时间】:2014-10-04 21:14:23
【问题描述】:

我在我的项目中使用了嵌入码头,但遇到了一些问题。我有这两个页面:

  • íindex.jsp
  • result.jsp

还有这两个 servlet:

  • 上传
  • 搜索

在 índex.jsp 中有一个上传文件的表单和上传 servlet 处理的上传过程,但是我应该向 índex.jsp 返回一条消息以告知上传是否完成。

request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);

这会将消息转发到索引页面,但 url 将是 /upload 并且我想成为索引。所以还有一些其他的方式来构建我的文件,也许让我的欢迎文件成为一些 servlet 而不是 índex.jsp?

【问题讨论】:

    标签: java jsp servlets


    【解决方案1】:

    最简单的解决方案是将上传 servlet 更改为使用重定向并使用请求参数而不是这样的属性:

    // upload servlet
    response.sendRedirect("index.jsp?message=YourMessage");
    

    然后在index.jsp 中使用request.getParameter("message") 或EL 来显示您的消息。

    【讨论】:

      【解决方案2】:

      这与 Jetty 无关。这是转发的默认行为。

      丑解:

      如果您想重写您的 URL,请改用重定向并通过会话传递参数。显示消息后,将其从会话中删除。

      更好的解决方案:

      通过 IndexServlet 更改上传 servlet 的名称。此 servlet 将处理 index.jsp 页面的 GET 和 POST 请求。在处理结束时,您将转发到您的 JSP 页面。通过这样做,您可以直接将表单发布到当前页面:

      <form action="index.jsp" method="POST" enctype="multipart/form-data">
          <!-- your fields ... -->
      </form>
      

      然后是你的 servlet:

      @WebServlet("index.jsp")
      public class IndexServlet extends HttpServlet {
          //using ... to avoid parameters and exceptions to be thrown
          @Override
          public void doGet(...) throws ... {
              //this method should only forward to your view
              RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
              rd.forward(request, response);
          }
      
          //using ... to avoid parameters and exceptions to be thrown
          @Override
          public void doPost(...) throws ... {
              //current implementation...
              //in the end, forward to the same view
              request.setAttribute("message", "Upload Sucedded!");
              RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
              rd.forward(request, response);
          }
      }
      

      更多信息:

      【讨论】:

      • 我的网站找不到 css 文件等...在码头,我将我的默认 servlet 设为 indexServlet 而不是网页。
      猜你喜欢
      • 2017-08-10
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2011-06-25
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      相关资源
      最近更新 更多