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


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

2 answers


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-name>MiServlet</servlet-name>  // nombre del servlet
    <servlet-class>EsteEsMiServlet</servlet-class>  // clase del servlet
    <servlet-name>MiServlet</servlet-name>   // nombre del servlet
    <url-pattern>/ruta</url-pattern>  // URL asignada al servlet

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

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):

public class AjaxServlet extends HttpServlet {

    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

    private String codificaEnJson(Object o) {
        //código para codificar un objeto como JSON...

Website that makes ajax calls using poll using setTimeout :

<!DOCTYPE html>
    <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>
    <script type="text/javascript">
        //función que hace poll
        (function poll() {
           //se llama a Timeout para ejecutar una acción
           setTimeout(function() {
                 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

    <!-- la tabla vacía, lista para recibir los datos desde el JSON -->
    <table id="tabla">

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