Highcharts In JSP And Servlets

Introduction

 
In this article, we will see how to develop Highcharts in JSP and Servlets. You can develop Highcharts in .Net, also. Suppose a project, that is developed in JSP and Servlet, is running. Now, we need a particular entry to calculate the total cost of the project in a number of days. While showing the graph, it is displaying a percentage and percentage ratio of how much it is pending with a pie chart drill down. Let's start.
 
 
Prerequisites
NOTE: When you install NetBeans, it will ask the platform on which you want to run the project. There are mostly two platforms: Apache Tomcat Server and Glassfish. If you select Apache Tomcat server, the project will run on that platform. I had selected a Glassfish server.
 
The difference between Apache Tomcat Server and Glassfish servers is - In apache Tomcat server, it only has the implementation of JSP and Servlets, whereas Glassfish or JBoss, has the full implementation of all servers, like Junit, Java EE and so on.
 
Open Netbeans Setup. On the left side of the pane, you will see these options:
 
 
You can also add servers from here if you missed that while installing. Now, let's start with the code.
 
Go To File->New Project.
 
 
 
Now, you will get a prompt.
 
 
 
Create Web Application ->Next. Give suitable name and destination.
 
 
Click Next. Now, see carefully. It will ask, " On which server do you want to run your project?" You can select the Servers from here. I selected GlassFish server.
 
 
Click Next. It will ask for Framework on which you want to develop these,  like Struts, Hibernate and so on. I haven’t selected any. Click Next and create a sample application .
 
 
 
 
Now, we will add a JSP page here and will name it as report.jsp.
 
Right-click on Web Pages and add new JSP.
 
 
Name it as Report.
 
 
It will ask for the location where you want to create it. See the details carefully and click Finish. You will see that Report.jsp is successfully created.
 
 
Now, just open that JSP page. JSP is nothing but an HTML Page. 
 
 
 
Here, you will see the title of the page and it's displaying Hello. Now, we will run the project and see what output are we getting. Just run the project.
 
 
When you run the project, you see that the Glassfish Server has started.
 
 
You will see Hello World! displayed. That means we have successfully created a JSP file and run our project and got output.
 
 
 
Now, we will add Highcharts JS which we had downloaded. Kindly Include a folder called JS.
 
 
Just copy all the Highchart JS files in the JS folder.
 
 
 
Now, let's include those JS in our JSP file.
 
 
 
Now, we will be exploring more on Highchart, such as - what kind of chart we want - say Pie, and in which color we want it. Just add these lines in the code to draw the chart. Now, as you have seen, there are three charts. So, we need three results sets, three divs, and three variables to store those outputs and display in chart.
 
For now, just add these lines:
  1. <script type="text/javascript">  
  2.             $(function() {              
  3.         Highcharts.theme = {  
  4.            colors: ['#058DC7''#50B432''#ED561B''#DDDF00''#24CBE5''#64E572''#FF9655''#FFF263''#6AF9C4'],  
  5.            chart: {  
  6.               backgroundColor: {  
  7.              linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },  
  8.              stops: [  
  9.                 [0, 'rgb(255, 255, 255)'],  
  10.                 [1, 'rgb(240, 240, 255)']  
  11.              ]  
  12.               },  
  13.               borderWidth: 2,  
  14.               plotBackgroundColor: 'rgba(255, 255, 255, .9)',  
  15.               plotShadow: true,  
  16.               plotBorderWidth: 1  
  17.            },  
  18.            title: {  
  19.               style: {  
  20.              color: '#000',  
  21.              font: 'bold 16px "Trebuchet MS", Verdana, sans-serif'  
  22.               }  
  23.            },  
  24.            subtitle: {  
  25.               style: {  
  26.              color: '#666666',  
  27.              font: 'bold 12px "Trebuchet MS", Verdana, sans-serif'  
  28.               }  
  29.            },  
  30.            xAxis: {  
  31.               gridLineWidth: 1,  
  32.               lineColor: '#000',  
  33.               tickColor: '#000',  
  34.               labels: {  
  35.              style: {  
  36.                 color: '#000',  
  37.                 font: '11px Trebuchet MS, Verdana, sans-serif'  
  38.              }  
  39.               },  
  40.               title: {  
  41.              style: {  
  42.                 color: '#333',  
  43.                 fontWeight: 'bold',  
  44.                 fontSize: '12px',  
  45.                 fontFamily: 'Trebuchet MS, Verdana, sans-serif'  
  46.   
  47.              }  
  48.               }  
  49.            },  
  50.            yAxis: {  
  51.               minorTickInterval: 'auto',  
  52.               lineColor: '#000',  
  53.               lineWidth: 1,  
  54.               tickWidth: 1,  
  55.               tickColor: '#000',  
  56.               labels: {  
  57.              style: {  
  58.                 color: '#000',  
  59.                 font: '11px Trebuchet MS, Verdana, sans-serif'  
  60.              }  
  61.               },  
  62.               title: {  
  63.              style: {  
  64.                 color: '#333',  
  65.                 fontWeight: 'bold',  
  66.                 fontSize: '12px',  
  67.                 fontFamily: 'Trebuchet MS, Verdana, sans-serif'  
  68.              }  
  69.               }  
  70.            },  
  71.            legend: {  
  72.               itemStyle: {  
  73.              font: '9pt Trebuchet MS, Verdana, sans-serif',  
  74.              color: 'black'  
  75.   
  76.               },  
  77.               itemHoverStyle: {  
  78.              color: '#039'  
  79.               },  
  80.               itemHiddenStyle: {  
  81.              color: 'gray'  
  82.               }  
  83.            },  
  84.            labels: {  
  85.               style: {  
  86.              color: '#99b'  
  87.               }  
  88.            },  
  89.   
  90.            navigation: {  
  91.               buttonOptions: {  
  92.              theme: {  
  93.                 stroke: '#CCCCCC'  
  94.              }  
  95.               }  
  96.            }  
  97.         };  
  98.   
  99.         // Apply the theme  
  100.         var highchartsOptions = Highcharts.setOptions(Highcharts.theme);  
Now, we will see how to create a chart. Here, you will see that I have created RSET_Depository function JavaScript and will be firing those in our Div and used a variable a. Similarly, I have done it for the other two variables, b and c.
  1. $('#RSET_DEPOSITORY').highcharts({  
  2.                     chart: {  
  3.                         plotBackgroundColor: null,  
  4.                         plotBorderWidth: null,  
  5.                         plotShadow: false  
  6.                     },  
  7.                     title: {  
  8.                         text: ' CRs Pending - Depository wise'  
  9.                     },  
  10.                     tooltip: {  
  11.                         pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'  
  12.                     },  
  13.                     plotOptions: {  
  14.                         pie: {  
  15.                             allowPointSelect: true,  
  16.                             cursor: 'pointer',  
  17.                             dataLabels: {  
  18.                                 enabled: true,  
  19.                                 color: '#000000',  
  20.                                 connectorColor: '#000000',  
  21.                                 format: '<b>{point.name}</b>: {point.percentage:.1f} %'  
  22.                             }  
  23.                         }  
  24.                     },  
  25.                     series: [{  
  26.                             type: 'pie',  
  27.                             name: 'Depository Share',  
  28.                             data: <%=a%>                             
  29.                         }]  
  30.                 });  
  31.             });  
Now, we will see the body section of this.
  1. <fieldset class="fieldset">  
  2.         <legend class="legend">Graph Details</legend>  
  3.          <tr>  
  4.             <td width="50%" >   
  5.                 <div id="RSET_DEPOSITORY" style="min-width: 250px; height: 350px; margin: 0 auto"></div>  
  6.             </td>  
  7.          </tr>  
  8.     </fieldset>  
Now, we will create a Servlet . Here, in the servlet, we will have to write queries in which we want to display total count and so on. As you can see in your solution, you do see source package.
 
 
Create a new servlet file and name it as report.java. Click Next and click the checkbox web.xml.
 
 
You have to add these file in web.xml so that whatever you write in a query on the servlet, it will display the result.
 
When you create a servlet, you will see HTTPserveltrequest and HTTPResponse.
 
 
 
Now, we will create another package. Inside that, we will create a java file called as DBConnection and we will write the code to connect to DB.
  1. try  
  2. {              
  3.     Class.forName("oracle.jdbc.driver.OracleDriver");           
  4.     ResourceBundle rsb = ResourceBundle.getBundle("nameofpackage .fn.utilites.MyResources");     
  5.  connection  = DriverManager.getConnection(rsb.getString("CONNECTION_URL"),rsb.getString("USERNAME"),rsb.getString("PASSWORD"));/**/              
  6. }  
  7. catch(Exception e)  
  8. {  
  9.     System.out.println(e);  
  10. }  
  11. }
Now, we will be using get connection and close connection and main entry point of our file .
  1. public void closeConnection()  
  2.  {  
  3.      try  
  4.      {  
  5.          if(!connection.isClosed())  
  6.          {     
  7.              connection.close();  
  8.          }  
  9.          System.out.println("Connection Closed");              
  10.      }  
  11.      catch(Exception e)  
  12.      {  
  13.          System.out.println(e);  
  14.      }  
  15.  }  
  16.    
  17.  public static void main(String args[])  
  18.  {  
  19.      DBConnection dbcon = new DBConnection();  
  20.      dbcon.getConnection();  
  21.      dbcon.closeConnection();/**/  
  22.  }  
Run the file. It will succefully get connected to our database. Just open your Servlet page.
 
 
And add these imports to initialize the DBConnection and prepared Statement
  1. private DBConnection dBConnection;  
  2. private Connection connection;  
  3. private PreparedStatement preparedStatement;  
Now, my final servlet code is
  1. if (auth.startsWith("NTLM "))  
  2.           {  
  3.               System.out.println("IF NTLM");  
  4.               byte[] msg = new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));  
  5.               int off = 0, length, offset;  
  6.               if (msg[8] == 1)  
  7.               {  
  8.                   System.out.println("IF IF NTLM");  
  9.                   byte z = 0;  
  10.                   byte[] msg1 = {(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S', (byte)'S', (byte)'P', z,(byte)2, z, z, z, z, z, z, z,(byte)40, z, z, z, (byte)1, (byte)130, z, z,z, (byte)2, (byte)2, (byte)2, z, z, z, z, z, z, z, z, z, z, z, z};  
  11.                   response.setHeader("WWW-Authenticate""NTLM " + new sun.misc.BASE64Encoder().encodeBuffer(msg1));  
  12.                   response.setStatus(response.SC_UNAUTHORIZED);  
  13.                   response.setContentLength(0) ;  
  14.                   response.flushBuffer();  
  15.               }  
  16.               else   
  17.               {  
  18.                   dBConnection =  new DBConnection();  
  19.                   System.out.println("in else");  
  20.                   connection = dBConnection.getConnection();  
  21.                  //   query3="SELECT SYSDATE- b.STATUS_AS_ON_DATE,b.PENDING_WITH,b.STATUS_AS_ON_DATE FROM AX_FRTNT_ENTRY_STATUS_MASTER_T b inner join ax_frtnt_entry_master_t a on b.ENTRY_ID = a.ENTRY_ID WHERE b.ENTRY_ID=?   ORDER BY 1 DESC";  
  22.                   // query3="SELECT STATUS_AS_ON_DATE,PENDING_WITH,COUNT(*) FROM AX_FRTNT_ENTRY_STATUS_MASTER_T WHERE ENTRY_ID=?  GROUP BY PENDING_WITH,STATUS_AS_ON_DATE ORDER BY 1 DESC ";  
  23.                 // final  query3="select TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY'),PENDING_WITH,count(pending_with) from ax_frtnt_entry_status_master_t where entry_id=?   GROUP BY PENDING_WITH,TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY') ORDER BY 1 DESC";  
  24.                  //4/7/2016 query3="select STATUS_AS_ON_DATE,TO_DATE(TO_CHAR(SYSDATE,'DD-MON-YY'))-TO_DATE(TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY')),PENDING_WITH,count(pending_with) from ax_frtnt_entry_status_master_t where entry_id=?   GROUP BY PENDING_WITH,STATUS_AS_ON_DATE ORDER BY 1 DESC";  
  25.                  // query3="select STATUS_AS_ON_DATE,PENDING_WITH ,COUNT(PENDING_WITH),(lead(STATUS_AS_ON_DATE,1) over (order by STATUS_AS_ON_DATE)-STATUS_AS_ON_DATE)*24/24 as Days_to_next_start from ax_frtnt_entry_status_master_t where entry_id=? GROUP BY STATUS_AS_ON_DATE,PENDING_WITH ORDER BY 1 ASC";  
  26.                  // query3=" select STATUS_AS_ON_DATE,TO_DATE(TO_CHAR(SYSDATE,'DD-MON-YY'))-TO_DATE(TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY')),PENDING_WITH,count(pending_with) from ax_frtnt_entry_status_master_t where entry_id=?   GROUP BY PENDING_WITH,STATUS_AS_ON_DATE ORDER BY 1 DESC";  
  27.                  // query3="select TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY'),PENDING_WITH,count(pending_with) from ax_frtnt_entry_status_master_t where entry_id=?   GROUP BY PENDING_WITH,TO_CHAR(STATUS_AS_ON_DATE,'DD-MON-YY') ORDER BY 1 DESC";  
  28.                   query3="SELECT PENDING_WITH, SUM(ROUND(Days_to_next_start)) AS Days_to_next_start  FROM ( select STATUS_AS_ON_DATE,PENDING_WITH, (lead(STATUS_AS_ON_DATE,1) over (order by STATUS_AS_ON_DATE)-STATUS_AS_ON_DATE)*24/24 as Days_to_next_start from ax_frtnt_entry_status_master_t where entry_id=? GROUP BY STATUS_AS_ON_DATE,PENDING_WITH ORDER BY 1 ASC) GROUP BY PENDING_WITH";  
  29.                  // query3="SELECT NVL(PENDING_WITH,'Not Assigned'),COUNT(*) FROM AX_FRTNT_ENTRY_MASTER_T WHERE ENTRY_ACTIVE_FLG = 'Y' AND ENTRY_CLOSED_STATUS = 'N' GROUP BY PENDING_WITH ORDER BY 2 DESC ";  
  30.                 //  query3="SELECT SYSDATE- b.STATUS_AS_ON_DATE,a.PENDING_WITH FROM AX_FRTNT_ENTRY_STATUS_MASTER_T  b  inner join ax_frtnt_entry_master_t a on b.ENTRY_ID = a.ENTRY_ID WHERE b.ENTRY_ID=?   ORDER BY 1 ASC";  
  31.                 //  query="SELECT EM.ENTRY_ID ENTRY_ID, UGM.USER_GROUP_NAME GROUP_NAME , EM.APPLICATION_NAME_PID APPLICATION_NAME_PID, NVL(TO_CHAR(EM.START_OF_ACTIVITY,'DD-MON-RRRR'),'NOT AVAILABLE') START_OF_ACTIVITY, EM.ACTIVITY_DESC || DECODE(NVL(TO_CHAR(NOA.CNT),' '),' ',' ','1', ' - ' || NOA.CNT || ' ATTACHMENT', ' - ' || NOA.CNT || ' ATTACHMENTS') ACTIVITY_DESC ,TO_CHAR(ESM.STATUS_AS_ON_DATE,'DD-MON-RRRR') STATUS_AS_ON_DATE , ESM.STATUS_DESCRIPTION STATUS_DESCRIPTION,EM.VALUE_ADD_BENEFIT VALUE_ADD_BENEFIT, EM.PROJECT_INITIATION_BY PROJECT_INITIATION_BY, UM.USER_NAME CREATED_BY, TO_CHAR(EM.ENTRY_CREATED_DATE,'DD-MON-RRRR') ENTRY_CREATED_DATE, EM.ENTRY_CREATED_BY ENTRY_CREATED_BY, NVL(EM.DEPOSITORY_NAME,'N.A.'), FLOOR(SYSDATE-STATUS_AS_ON_DATE) PENDING_COUNT, NVL(EM.PENDING_WITH,' ') PENDING_WITH, NVL(EPM.PRIORITY,'5') PRIORITY,TO_CHAR(ESM.TARGET_AS_ON_DATE,'DD-MON-RRRR')TARGET_AS_ON_DATE from ax_frtnt_entry_master_t em , ax_frtnt_user_group_master_t ugm, ax_frtnt_report_user_master_t um, ax_frtnt_entry_status_master_t esm, (select count(*) cnt, entry_id from ax_frtnt_cr_file_t group by entry_id) noa, AX_FRTNT_ENTRY_PRIORITY_T epm where epm.entry_id (+) = em.entry_id and noa.entry_id (+) = em.entry_id and em.ENTRY_CLOSED_STATUS = 'N' and em.user_group_id = ugm.user_group_id and em.entry_created_by = um.user_id and em.entry_id = esm.entry_id and esm.status_entry_date = (select max(status_entry_date) from ax_frtnt_entry_status_master_t where entry_id = em.entry_id) order by GROUP_NAME,APPLICATION_NAME_PID,EM.DEPOSITORY_NAME,TO_DATE(START_OF_ACTIVITY),1 ";   
  32.                   System.out.println(query3);  
  33.                  //  PreparedStatement prepareresolved =connection.prepareStatement(query2);  
  34.                // prepareresolved.setString(1, request.getParameter("ENTRY_ID"));  
  35.                   // ResultSet resultresolved = prepareresolved.executeQuery();  
  36.                   // request.setAttribute("resultresolved", resultresolved);  
  37.                 //  preparedStatement = connection.prepareStatement(" SELECT PENDING_WITH,COUNT(*) FROM AX_FRTNT_ENTRY_MASTER_T WHERE ENTRY_ID=? AND ENTRY_ACTIVE_FLG='Y' AND ENTRY_CLOSED_STATUS='N' GROUP BY PENDING_WITH ORDER BY 1 DESC ");  
  38.                   PreparedStatement RSET_DEPOSITORY =connection.prepareStatement(query3);  
  39.                   RSET_DEPOSITORY.setString(1, request.getParameter("ENTRY_ID"));  
  40.                   ResultSet RSET_DEPOSITORYnew=RSET_DEPOSITORY.executeQuery();  
  41.                   request.setAttribute("RSET_DEPOSITORYnew", RSET_DEPOSITORYnew);  
  42.                   RequestDispatcher rd = request.getRequestDispatcher("ViewEntryDetails.jsp");  
  43.                   rd.forward(request, response);  
  44.               }  
  45.           }  
  46.             
  47.         // RequestDispatcher rd = request.getRequestDispatcher("ViewEntryDetails.jsp");  
  48.         //  rd.forward(request, response);  
  49.       }   
  50.       catch(Exception e)  
  51.       {  
  52.           System.out.println(e);  
  53.       }  
  54.       finally   
  55.       {         
  56.           dBConnection.closeConnection();  
  57.           out.close();  
  58.       }  
I have created a resource file under DBconnection.Java Package and named that resource file Myresources.Properties and passed connection _url, username, and password.
 
 
Now, switch back to JSP page. We will be passing those resultsets in the variables which we had defined already as a,b and c.
 
 
 

Conclusion

 
This was all about developing Highcharts. I hope this article was helpful. All the Best !! Cheers!!