有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用ajax在JSP中获取“request.setAttribute”属性

我有一个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.");

这能行吗?还是我必须以不同的方式设定信息


共 (1) 个答案

  1. # 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")%>
    

    希望这有帮助