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
One approach is to expose your Java functionality as a REST service.
Jersey REST end point
@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);
});
});
I would use jquery and do ajax calls back to the server. Once the ajax call is finished, you can then update your index.html file using javascript and not have to reload the page.
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!