How to make Ajax requests in Java [closed]

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 should update another ComboBox with all cities.

I'm 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'm developing now needs to be in Java and even researching I could not fully understand how Ajax works in this language.

I need a more practical and accurate example to get this to work.

Thanks in advance.

    
asked by anonymous 15.10.2018 / 12:26

1 answer

0

In the case of java, just make the request via Ajax to an address that will do the processing. The ideal is to request a Servlet. Inside this servlet, you would do the processing and the return of it, it would be 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.
}

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 an example, as I mentioned. There are several ways to do this, by passing JSON as a return and all.

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

    
15.10.2018 / 15:54