【问题标题】:Is it possible to execute the request.getRequestDispatcher from the post call of a javascript function?是否可以从 javascript 函数的 post 调用中执行 request.getRequestDispatcher?
【发布时间】:2017-08-07 21:46:09
【问题描述】:

我通过“post”调用 java 控制器并发送一个表单,我对其进行处理,然后将请求中的一些属性发送回响应,我希望使用 javascript 可以处理它们。有可能吗?

我的控制器:

  /**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}
/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException 
{
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter())
    {
        Respuesta r;
        request.setAttribute("MensajeRespuesta", "");
        request.setAttribute("StatusRespuesta", "");
        ServletInputStream aaaa = request.getInputStream();

    if (request.getParameter("btnGuardarDiio") != null && !"".equals(request.getParameter("btnGuardarDiio")))
        {
            //Code...
            request.setAttribute("MensajeRespuesta", r.getMensaje());
            request.setAttribute("StatusRespuesta", r.isStatus());
            request.setAttribute("StatusGuardado", true);
     request.getRequestDispatcher("/pages/maestros/crudAnimal.jsp").forward(request, response); 

        }
  .
  .
  .

我的 JSP 脚本:

 <script>
        $('#myFormSubmit').click(function(e){
                $.post('crudAnimal?btnGuardarDiio=eliminar', $('#formGuardarDIIO').serialize(), 
                  function(responseText,respuesta){
                    if(respuesta = "success"){
                     // What do I have to do so that the "response" of the controller redirects to the page and can receive the attributes?
                   }

            });

            });
 </script>

谢谢!

【问题讨论】:

    标签: javascript java servlets


    【解决方案1】:

    在 javascript 客户端上,您根本无法访问在服务器端设置的任何请求/响应属性。它属于服务器,不属于任何 http 响应负载。

    但是,您的帖子似乎表明您正在jsp 页面上编写该javascript 代码。如果根据请求重新生成该 jsp 输出,那么您可以使用它。通过 jsp 上的 java 代码访问请求属性(即在服务器端处理),以便生成的 js 代码发送回客户端,包含您想要的内容。

    here 你有一些关于 jsps 如何工作的基本文档。如果您想了解其工作原理,我建议您阅读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多