David Stalder
David Stalder

Reputation: 23

Get "request.setAttribute" Attributes in JSP with ajax

I hava a Jsp Site, in which the user can type in some data. This data is then sent to a servlet. In the servlet the data is then stored in a database. I'm making this request with ajax. In the servlet I set a message, which should be displayed on the jsp Site after submiting. My Question is, how do I get this String from my servlet to my jsp site and display it in a paragraph?

My Ajax function:

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

                    });
            });
        }
    }
}

And the part of my servlet where I set the Message:

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

Can this work? Or do I have to set the message diffrently?

Upvotes: 1

Views: 1982

Answers (1)

Ele
Ele

Reputation: 33726

Via javascript you won't be able to get that attribute.

I think you can do it with one of these two approaches:

1.- Send that message as a response from the servlet like this, this is thinking your app is a single page one:

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

Then, in your javascript code you can show it whatever you need on your page.

2.- After receive the ajax response, execute a redirect action. You can use one of these approaches:

// 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";

In your JSP, you can get the attribute in some ways, the easiest way is:

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

Hope this helps!

Upvotes: 1

Related Questions