Zhunder
Zhunder

Reputation: 83

Display loading state while java code on jsp site is executed

I found similar things, but none of them actually fits my wishes.

I´ve got one jsp page where the java code which takes 10-30 seconds to finish (i am getting something from a database and build charts) and i want to add a nice loading image in the middle of the page and make it fade off when it has finished loading.

Upvotes: 1

Views: 3464

Answers (1)

bprasanna
bprasanna

Reputation: 2453

This is not a straight forward solution. But, it is able to achieve your requirement by using iframe.

My trials with single page jsp failed as the loading of the page didn't happen till the process inside JSP is finished.

Following is the workaround i used:

  1. Create the main JSP (assume index.jsp) page where display part is handled
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Testing the loading</title>
    <script type="text/javascript">
    function processRecords(){
        document.getElementById("mainContent").src = "process.jsp";
    }
    </script>
</head>
<body onload="processRecords()">
    <iframe id="mainContent" width="100%" style="border: none" seamless src="loader.jsp"></iframe>
</body>
</html>
  1. Create a JSP/HTML (assume loader.jsp) with loader display part
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Processing</title>
</head>
<body>
<img src="images/loader.gif" style="position:absolute; top:0; bottom:0; left:0; right:0; margin:auto;"/>
</body>
</html>
  1. Create a JSP (assume process.jsp) with actual processing & results display
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Processing</title>
</head>
<body>
    <%
        //Following is a manual sleep simulating a process 
        try {
            //Sleep for 10 seconds
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            out.write("Error occurred while processing");
        }
        out.write("Done!");
    %>
</body>
</html>
  1. Working

When main JSP page (index.jsp) loads it will be loading with iframe src pointing to the loader JSP page (loader.jsp). So, initially the loader gif image will be displayed. The onload method in main JSP page invokes a javascript which in turn invokes the actual processing JSP page (process.jsp). Till the processing JSP page returns results the loader page in iframe won't be replaced simulating, thus simulating the loading before processing in Java code.

Upvotes: 2

Related Questions