Is it possible to run a servlet from a Thread class?

2

I'm doing a web application with JSP. This application has to show the result of a query in a table. The difficulty is that this has to be shown when the application is opened (url), without pressing any button. I thought about doing a Thread that runs every n time and this one called the servlet (controller) to do the rest (intance the class in which it is querying the database and deliver the data to the jsp), but actually I do not know if that can be done or if there is another, more optimal way to do it.

    
asked by elsa 14.06.2016 в 22:57
source

2 answers

1

It is not a good idea, create Threads to organize the execution of the code of a web application is the responsibility of the container, e.g. Tomcat.

What you can do is register your servlet in web.xml to listen to a specific URL:

<servlet>
    <servlet-name>MiServlet</servlet-name>  // nombre del servlet
    <servlet-class>EsteEsMiServlet</servlet-class>  // clase del servlet
</servlet>
<servlet-mapping>
    <servlet-name>MiServlet</servlet-name>   // nombre del servlet
    <url-pattern>/ruta</url-pattern>  // URL asignada al servlet
</servlet-mapping>

This way every time you enter /ruta the servlet will be executed, without the need to press a button or other user action, as long as the servlet overwrites the doGet method.

    
answered by 14.06.2016 в 23:26
1

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();
}
    
answered by 14.06.2016 в 23:33