Skip to content

How to show loop results on html page in real time Java Spring

I would like to show loop results on html page in real time. I use Java , Spring, thymeleaf, javascript. The loop is below. Instead of system out print I would like it to be displayed on html page.

    public String testProgress() {
        for (int i = 1; i <= 100; i++) {
                System.out.println("20 %");
            }else if (i==40){
                System.out.println("40 %");
            }else if (i==60){
                System.out.println("60 %");
            }else if (i==80){
                System.out.println("80 %");
            }else if (i==100){
                System.out.println("100 %");
        return null;


You can do this using Server Sent Events and htmx.

First, create a @GetMapping method to expose the SSE channel:

  private SseEmitter sseEmitter;

    public SseEmitter progressEvents() {
        sseEmitter = new SseEmitter(Long.MAX_VALUE);
        sseEmitter.onCompletion(() ->"SseEmitter is completed"));
        sseEmitter.onTimeout(() ->"SseEmitter is timed out"));
        sseEmitter.onError((ex) ->"SseEmitter got error:", ex));

        return sseEmitter;

Next, have your method that start the process you want to monitor. This can be any method. In this example, I used a POST:

    public String generatePdf() {
        for(int progress = 0; progress <=100;progress++) {
          int progress = 0
          String html = """
                    <div id="progress-container" class="progress-container"> 
                        <div class="progress-bar" style="width:%s%%"></div> 


        return "index";

In your Thymeleaf template:

<div hx-sse="connect:/progress-events">
    <button hx-post="/" hx-swap="none">Show progress</button>
    <div style="margin-bottom: 2rem;"></div>
    <div id="progress-wrapper" hx-sse="swap:message">
<script type="text/javascript" th:src="@{/webjars/}"></script>
  • hx-sse (on the outer div): Tells htmx on what SSE channel to connect
  • hx-post: Tells htmx to do a POST when the button is clicked
  • hx-swap: Tells htmx that the respone of the POST should not be used to replace the innerHTML of the button
  • hx-sse (on the inner div): Tells htmx to swap the innerHTML of progress-wrapper with the HTML that is sent via the Server Sent Events

One tricky thing is that the HTML cannot contain newlines, that is why that text block has backslashes at the end of each line.

You can see a full example at It is slightly more complicated in the sense that it uses Spring Security and keeps track of SseEmitters per user so that the progress is sent to all open browser tabs where the user is logged on.