How to make Ajax requests in Java [closed]

closed . This question needs details or to be clearer and is not currently accepting answers.

want to improve this question? Add details and make it clearer what problem is being solved by editing this post .

Closed 2 years ago .

improve this question

Good Morning

I am developing a Web application where I need something simple: when the user selects a state in a ComboBox , the system should update another ComboBox with all cities.

I am a .NET programmer and in this model I would use a schema 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 researching I could not understand how Ajax works in this language.

I need a more practical and exact example to be able to do this work.

Right now, thank you.

Author: Matheus Socoloski Velho, 2018-10-15

1 answers

In the case of java, just make the request via Ajax to an address that will do the processing. Idela is to request a Servlet. Within this servlet, vc would do the processing and return of it, it would be this your other combobox.

Basic example:

first the 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 cited. There are several ways to do this, passing JSON as return and all more.

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

 0
Author: Maycon Stanguine, 2018-10-22 14:42:12