javascripthtmlspring-mvcjsp-tags

How to reload a HTML table without refreshing the whole page while working with Spring MVC


I am using Spring MVC , example.jsp file with Javascript.
I have been stuck on this for a long time.

Is it possible to use Javascript to laod new data from DB into HTML tables without refreshing the whole page?

I just don't want my whole page being replaced when new data is loaded into table with some event.


Solution

  • If you want to reload a part of you page using JavaScript, basically AJAX.
    This is how you should do it.

    Client Side

    Let's assume that you're using jQuery as a JavaScript Framework.
    You'll need to use jQuery.ajax() in the Client Side.

    var successHandler = function( data, textStatus, jqXHR ) {
      // After success reload table with JavaScript
      // based on data...
    };
    
    var errorHandler = function( jqXHR, textStatus, errorThrown ) {
      // Error handler. AJAX request failed.
      // 404 or KO from server...
      alert('Something bad happened while reloading the table.');
    };
    
    var reloadData = function() { 
      // Process your request
      var request = new Object();
      request.id = 'some id'; // some data
    
      // Make the AJAX call
      jQuery.ajax({
        type       : 'POST',
        url        : 'http://domain/context/reload-data-url',
        contentType: 'application/json',
        data       : JSON.stringify(request)
        success    : successHandler,
        error      : errorHandler
      });
    };
    

    Call the reloadData() function when you need to reload the table.

    Server Side

    You're using Spring MVC. Then your Controller should look like:

     // Spring MVC Controller
     @Controller
     public class ReloadDataController {
    
       // Request Mapping
       @RequestMapping(value = '/reload-data-url', method = RequestMethod.POST)
       @ResponseBody
       public ResponseEntity<String> processReloadData(@RequestBody String body) {
    
         // Get your request
         JSONObject request = new JSONObject(body);
         String id = request.getString("id"); // Here the value is 'some id'
    
         // Get the new data in a JSONObject
         JSONObject response = new JSONObject();
         // build the response...
    
         // Send the response back to your client
         HttpHeaders headers = new HttpHeaders();
         headers.add("Content-Type", "application/json; charset=utf-8");
         return new ResponseEntity<String>(response.toString(),
                    headers, HttpStatus.OK);
       }
    
     }
    

    You don't have to use JSON but I think this is the best way. Hope this will help you.