How to make Ajax requests in Java

Asked

Viewed 953 times

0

Good Morning

I’m developing a web application where I need something simple: when the user selects a state in a Combobox, the system shall update another Combobox with all cities.

I am programmer . NET and in this model I would use a scheme with Updatepanels and Triggers to perform this action without reloading the entire page. However, the application I am developing now needs to be in Java and even searching I could not understand properly the functioning of Ajax in this language.

I need a more practical and accurate example to make it work.

From now on, thank you.

  • is working with jsf? If so, which version?

  • Ajax works in Javascript. Java you would ideally do everything REST. So, there shouldn’t be anything about Ajax in your Java code. Except, of course, if you’re using a framework that also produces all the CSS, Javascript and/or HTML, especially if it’s something other than REST, but then you’d have to say what that framework is.

  • I think I ended up not being very clear Victor, I didn’t want to put Ajax inside Java, just understand how the calls to a Java code work because I have more knowledge in ASP.NET and in this language I use another method to make this type of request. Anyway, I got it sorted out. Thank you.

1 answer

0


In the case of java, just make the request via Ajax to an address that will do the processing. The idela is to request a Servlet. Inside this Servlet, you would do the processing and return of it, it would be this your other combobox.

Basic example:

First request via Ajax:

function getComboBox() {
    var xhttp = null;
    if (window.XMLHttpRequest) {
        //code for modern browsers
        xhttp = new XMLHttpRequest();
    } else {
        // code for old IE browsers
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.onreadystatechange = function() {
        if(this.readyState == 3) {
            console.log("Processando");
        } 
        if(this.readyState == 4 && this.status == 200) {
          document.getElementById("seuSelectID").innerHTML = this.responseText;
          console.log("Pronto");
        }
    };
    xhttp.open("POST", "/SuaAplicacao/SuaServlet.java", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("action=filtrar&idEstado=1"); // Exemplo de passagem de parametros.
}

A Servlet:

    // imports omitidos

    @WebServlet("/ajaxservlet")
    public class AjaxServlet extends HttpServlet {

       protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.setContentType("text/html;charset=UTF-8");
           String action = "";
           // action foi passado pelo ajax
           if(request.getParameter("action") != null && request.getParameter("action".equals("filtrar")) {

             // aqui vc faz a busca usando os métodos de sua aplicação. O id foi passado pelo ajax.
             List<SeuObjetoCidade> lista = SeuDAO.listaCidadesByIdDoEstado(Long.parseLong(request.getParameter("idEstado")));

             // Este objeto, será o retorno que o ajax utilizará no this.responseText
             PrintWriter pw =  response.getWriter();
             for(SeuObjetoCidade obj: lista) {
                pw.println("<option value='"+obj.getId()+"'>");
                pw.println(obj.getNome());
                pw.println("</option>");
             }
             pw.close();
           }

       }
    }

Above is just one example, as I mentioned. There are several ways to do this, passing JSON as return and all.

Another point, if you want some framework to help in this issue Java / Ajax, search for DWR.

  • 1

    Thank you very much Maycon, your explanation was clear and concise. I managed to make my code work and now yes I understand how it works. Just an addendum, you are passing a 'idState' variable in JS and picking up a 'id' variable in Java, I had to fix this in my code.

  • Well observed Matheus! I made the change for better understanding.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.