Calling Java Method from html without using a servlet

后端 未结 3 710
借酒劲吻你
借酒劲吻你 2021-01-27 12:59

I have my index.html that has a certain view, and I want to update this view (without redirecting or reloading the page) by calling a java method, that consumes a w

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-27 13:58

    You can use servlet, but you have to use Ajax to make asynchronous calls to the servlet without reloading the full page.

    $.ajax({
        type:"post",
        url: "redirector?operacion=515&id_orden="+id_orden+"&id_acto="+id_acto, 
        dataType: "text",
        success: function(response){
            //Do the stuffs you need with the response here.
        },
        error: function(response,error){
            console.log(response);
            console.log(error);
        }
    
    });
    

    This is an example of ajax call with jquery where "redirector" is the name of my servlet and on my servlet this is the code that I have:

    case 515:
    
        PrintWriter writer = response.getWriter();
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
    
        try {
        Integer id_acto = Integer.parseInt(request.getParameter("id_acto"));
        String resultado = consultasBBDD.consultarNivelesPorActo(id_acto);
        writer.print(resultado);
    
        } catch (Exception e) {
        System.out.println("Error recuperando niveles de exigencia");
        }
    
        writer.flush();
        writer.close();
       break;
    

    On the dataType attribute of the ajax call you have to specify the type of the response. Also remember that on your servlet you cant do the request.getRequestDispatcher(urlToGo); when you make ajax calls.

    Hope this help and sorry for my horrible english!

提交回复
热议问题