【问题标题】:Get "request.setAttribute" Attributes in JSP with ajax使用 ajax 在 JSP 中获取“request.setAttribute”属性
【发布时间】:2017-12-11 14:02:55
【问题描述】:

我有一个 Jsp 站点,用户可以在其中输入一些数据。然后将此数据发送到 servlet。然后在 servlet 中将数据存储在数据库中。 我正在用 ajax 提出这个请求。在servlet中我设置了一条消息,提交后应该显示在jsp站点上。我的问题是,如何从我的 servlet 获取这个字符串到我的 jsp 站点并在一个段落中显示它?

我的 Ajax 函数:

function submitForms() {
    if (checkSelect()) {
        if (checkWeight()) {
            $("form").each(
                function() {
                    var $form = $(this);
                    $.post($form.attr("action"), $form.serialize(),
                        function(response) {

                    });
            });
        }
    }
}

还有我设置消息的 servlet 部分:

request.setAttribute("sucMessage", "LBV Teil wurde in der Datenbank gespeichert.");

这行得通吗?还是我必须以不同的方式设置消息?

【问题讨论】:

    标签: java jquery ajax


    【解决方案1】:

    通过 javascript,您将无法获得该属性。

    我认为您可以使用以下两种方法之一:

    1.- 像这样将消息作为 servlet 的响应发送,这是认为您的应用是单页的:

    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    out.print("{\"sucMessage\": \"LBV Teil wurde in der Datenbank gespeichert.\"}");
    out.flush();
    

    然后,在您的 javascript 代码中,您可以在页面上显示您需要的任何内容。

    2.- 收到ajax响应后,执行重定向动作。您可以使用以下方法之一:

    // use this to avoid redirects when a user clicks "back" in their browser
    window.location.replace('http://somewhereelse.com');
    
    // use this to redirect, a back button call will trigger the redirection again
    window.location.href = "http://somewhereelse.com";
    
    // given for completeness, essentially an alias to window.location.href
    window.location = "http://somewhereelse.com";
    

    在你的JSP中,你可以通过一些方式获取属性,最简单的方法是:

    <%=request.getAttribute("sucMessage")%>
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 1970-01-01
      • 2012-06-04
      • 2011-04-04
      • 1970-01-01
      • 2014-03-07
      • 2016-03-04
      • 1970-01-01
      相关资源
      最近更新 更多