繁体   English   中英

从HTML调用Java方法而不使用Servlet

[英]Calling Java Method from html without using a servlet

我有一个具有特定视图的index.html ,并且我想通过调用Java方法来更新此视图(而无需重定向或重新加载页面),该方法消耗Web服务并检索数据。 我想在index.html显示数据。 我尝试使用servlet,但是它重定向到另一个URL,而这不是我想要的。

有没有办法在我的index.html调用Java或显示Java类的属性?

我将使用jquery并做ajax调用返回到服务器。 ajax调用完成后,您可以使用javascript更新index.html文件,而不必重新加载页面。

您可以使用servlet,但是必须使用Ajax对servlet进行异步调用,而无需重新加载整个页面。

$.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);
    }

});

这是使用jquery进行ajax调用的示例,其中“重定向器”是我的servlet的名称,在我的servlet上,这是我拥有的代码:

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;

在ajax调用的dataType属性上,您必须指定响应的类型。 还要记住,在您的servlet上,您不能执行request.getRequestDispatcher(urlToGo); 当您进行ajax调用时。

希望能有所帮助,对不起我的英语不好!

一种方法是将Java功能公开为REST服务。

泽西岛REST终点

@Path("/rest/emp/")
public class EmployeeService {
    @GET
        @Path("/{param}")
        public EmployeDTO getMsg(@PathParam("param") String id) {



            return getEmployeeDetails(id);

        }

    }

EmployeDTO.java

String name;
String id;
String address;
//getters and setters

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Sample Page</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="employee.js"></script>
    </head>

    <body>
        <div>
            <p id="eid">The ID is: </p>
            <p id="eName">The Employee Name: </p>
            <p id="eAddress">The Employee Address:</p>
        </div>
    </body>
</html>

employee.js

$(document).ready(function() {
    $.ajax({
        url: "/rest/emp/10" (Your Rest end point URL)
    }).then(function(data) {
       $('#eid').append(data.id);
       $('#eName').append(data.name);
       $('#eAddress').append(data.address);

    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM