I recommend having a Servlet that provides the information you need via JSON and polling from your view through Ajax to refresh the content.
I'll give you an example of both.
Servlet that supports ajax calls (can be any servlet in fact, the name is only as a demonstration):
@WebServlet("/ajax/ajaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DataService dataService = new DataService();
//método que obtiene los datos desde base de datos u otro
List<Data> dataList = dataService.getData();
//Obtenemos el escritor de la respuesta
//para escribir el contenido de la respuesta manualmente
Writer writer = response.getWriter();
//escribimos los datos de la variable data como JSON
writer.write(codificaEnJson(dataList));
}
private String codificaEnJson(Object o) {
//código para codificar un objeto como JSON...
}
}
Website that makes ajax calls using poll using setTimeout
:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uso de ajax</title>
<!--
Se asume que tienes jquery en tu proyecto
y se encuentra en una ruta como
Web Resources/js/jquery.js
Cambia la ruta adecuadamente
-->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
//función que hace poll
(function poll() {
//se llama a Timeout para ejecutar una acción
//cada
setTimeout(function() {
$.ajax({
url: "${pageContext.request.contextPath}/ajax/ajaxServlet", //URL del servlet
success: function(data) {
//función para armar la tabla desde los valores
},
dataType: "json",
complete: poll //al finalizar, se vuelve a llamar a la función poll de manera que es eterno
});
}, 30000); //se ejecuta cada 30 segundos, puedes configurarlo al tiempo que requieras
})();
</script>
<!-- la tabla vacía, lista para recibir los datos desde el JSON -->
<table id="tabla">
</table>
</body>
</html>
To convert an object to JSON, you can use Jackson or Gson . Here is an example of how to do it with Jackson:
private String codificaEnJson(Object o) {
//código para codificar un objeto como JSON...
return mapper.writeValueAsString(o);
}
ObjectMapper mapper;
public void init(ServletConfig config)
throws ServletException {
mapper = new ObjectMapper();
}