1

On click of a button on a page,I want to display a Bar chart.I am able to display bar chart,but chart is opening in a new window,but I want to display it on same page.

I am clicking on following button on transactionData.jsp to display chart :

In transactionData.jsp : Modifed :

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script>
    $(function(){
        $("#submitButton").click(function(e){
            e.preventDefault();
            $.ajax({type: "GET",
            url: "<s:url action='displayChartAction'/>",
            success:function(result){
                $("#chartOutput").html(result);
            }
        });
     });
    });
</script>


<s:head theme="ajax" debug="true"/>
<title>Hello World</title>
</head>
<body bgcolor="grey">
<s:form>
      <s:datetimepicker label="Select From" name="transactionBean.fromDate" displayFormat="dd-MM-yy" required="true" />  
      <s:datetimepicker label="Select To" name="transactionBean.toDate" displayFormat="dd-MM-yy" required="true" />
      <s:optiontransferselect
        label="Channels"
        name="transactionBean.leftChannels"
        leftTitle="Unselected Channels"
        rightTitle="Selected Channels"
        list="transactionBean.leftChannelsList"
        multiple="true"
        headerKey="-1"
        doubleList="transactionBean.rightChannelsList"
        doubleName="transactionBean.rightChannels"
        doubleHeaderKey="-1"
        doubleHeaderValue="Selected Values"
      /> 

      <!-- Transaction Types -->

      <s:optiontransferselect

        label="transaction Types"
        name="transactionBean.leftTransTypes"
        leftTitle="Unselected Transaction Type"
        rightTitle="Selected Transaction Type"
        list="transactionBean.leftTransTypesList"
        multiple="true"
        headerKey="-1"
        doubleList="transactionBean.rightTransTypesList"
        doubleName="transactionBean.rightTransTypes"
        doubleHeaderKey="-1"
        doubleHeaderValue="Selected Values"
      />  


      <!-- Bics -->
       <s:optiontransferselect
        label="Bics"
        name="transactionBean.leftBics"
        leftTitle="Unselected Bics"
        rightTitle="Selected Bics"
        list="transactionBean.leftBicsList"
        multiple="true"
        headerKey="-1"
        doubleList="transactionBean.rightBicList"
        doubleName="transactionBean.rightBics"
        doubleHeaderKey="-1"
        doubleHeaderValue="Selected Values"
      />     
    <div id="chartOutput"> 

    </div>
      <h3>All Records:</h3>  
      <table border="true"> 
        <s:iterator  value="listTransBean">   
             <tr>
             <td>
            <s:property value="dateTime"/><br/>
            </td>
            <td>   
            <s:property value="channel"/><br/>
            </td>
            <td>   
            <s:property value="transactionType"/><br/>
            </td>
            <td>   
            <s:property value="bic"/><br/>
            </td>
            <td>
            <s:property value="volume"/><br/>
            </td>
            </tr>     

        </s:iterator>  
        </table>

       <s:submit id="submitButton" value="Show Chart" align="center" />
       <s:submit value="Fetch Data" align="center" action="displayDataAction" />

   </s:form>
</body>
</html>

displayChartAction is mapped in struts.xml like :

<action name="displayChartAction" 
        class="com.tutorialspoint.struts2.jFreeChartAction" 
        method="execute">
             <result name="success" type="chart">
                <param name="value">chart</param>
                <param name="type">jpeg</param>
                <param name="width">600</param>
                <param name="height">400</param>
            </result> 
</action>

and JfreeChartAcction is as below :

    public class JfreeChartAction extends ActionSupport {

    private JFreeChart chart;

    private TransactionBean transactionBean;
    private TransactionDao transactionDao;
    private List<TransactionBean> listTransBean;

    public List<TransactionBean> getListTransBean() {
        return listTransBean;
    }

    public void setListTransBean(List<TransactionBean> listTransBean) {
        if(listTransBean == null){
            listTransBean = new ArrayList<TransactionBean>();
        }
        this.listTransBean = listTransBean;
    }

    public TransactionDao getTransactionDao() {
        return transactionDao;
    }

    public void setTransactionDao(TransactionDao transactionDao) {
        this.transactionDao = transactionDao;
    }

    public TransactionBean getTransactionBean() {
        if(transactionBean==null){
            transactionBean = new TransactionBean();
        }
        return transactionBean;
    }

    public void setTransactionBean(TransactionBean transactionBean) {
        this.transactionBean = transactionBean;
    }
    // This method will get called if we specify <param name="value">chart</param>
    public JFreeChart getChart() {
        return chart;
    }

    public void setChart(JFreeChart chart) {
        this.chart = chart;
    }

    public String execute() throws Exception {
        System.out.println("Inside Execute: Start");

        System.out.println("From date:"+getTransactionBean().getFromDate());
        System.out.println("From date:"+getTransactionBean().getToDate());
        System.out.println("leftChannels:"+getTransactionBean().getLeftChannels());
        System.out.println("RightChannels:"+getTransactionBean().getRightChannels());
        System.out.println("leftChannelsList:"+getTransactionBean().getLeftChannelsList());
        System.out.println("rightChannelsList"+getTransactionBean().getRightChannelsList());
        System.out.println("Left Trans type List"+getTransactionBean().getLeftTransTypesList());
        System.out.println("Right Trans type List"+getTransactionBean().getRightTransTypesList());
        System.out.println("Right Trans Type"+getTransactionBean().getRightTransTypes());
        System.out.println("Left Bic List"+getTransactionBean().getLeftBicsList());
        System.out.println("Right Bic List"+getTransactionBean().getRightBicList());
        System.out.println("Right Bics"+getTransactionBean().getRightBics());
        System.out.println("Inside Execute: End");
        List<TransactionBean> list = transactionDao.fetchChartData(getTransactionBean());

        System.out.println("List Size:"+list.size());
        Iterator<TransactionBean> itr = list.iterator();

        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        while(itr.hasNext()){

            TransactionBean transBean = (TransactionBean)itr.next();
            System.out.println("Volume:"+transBean.getVolume());
            System.out.println("Date Time:"+transBean.getDateTime().toString());
            System.out.println("Channel:"+transBean.getChannel());
            dataSet.setValue(transBean.getVolume(),transBean.getDateTime(),"Channel");
        }

        chart = ChartFactory.createBarChart(
                   "Bar Chart",     //Chart title
                "",     //Domain axis label
                "TRANSACTIONS",         //Range axis label
                dataSet,         //Chart Data 
                PlotOrientation.VERTICAL, // orientation
                true,             // include legend?
                true,             // include tooltips?
                false             // include URLs?
            );
        chart.setBorderVisible(true);
        System.out.println("Execute Ends");
        return SUCCESS;

        }

    public String display(){
        System.out.println("Inside display");   
        List<String> leftChannelsList = null;

        leftChannelsList = transactionDao.fetchChannels();
        setTransactionBean(new TransactionBean());
        getTransactionBean().setLeftChannelsList(leftChannelsList);

        List<String> leftTransTypesList = null;
        leftTransTypesList = transactionDao.fetchTransactionTypes();
        getTransactionBean().setLeftTransTypesList(leftTransTypesList);

        List<String> leftBicsList = null;
        leftBicsList =  transactionDao.fetchBics();
        getTransactionBean().setLeftBicsList(leftBicsList);

        return SUCCESS; 
    }

    public JfreeChartAction(){
        System.out.println("Inside Constructor");
    }


    public String fetchTransactionsData(){
        System.out.println("Inside Fetch Transaction Data");
        List<TransactionBean> list = transactionDao.fetchTransactionsData(getTransactionBean());
        setListTransBean(list);
        return SUCCESS;
    }
}

Can anyone suggest,how i can display Bar chart on same page, i.e on transactionData.jsp itself rather than in a new window.

Thanks in advance.

javaguy
  • 927
  • 2
  • 16
  • 37
  • is there any restriction on using form tag instead of s:submit of struts? – SMA Oct 26 '14 at 09:43
  • Thanks Almas for your reply.I have form tag also on my transactionData.jsp.However as i needed to call two different methods of same action class on click of two buttons,I used s:submit in manner mentioned above. – javaguy Oct 26 '14 at 10:49
  • If you use two different methods then you should see http://stackoverflow.com/a/23415759/573032 – Roman C Oct 26 '14 at 13:38
  • Thanks Roman.Code for invoking two methods of same action on click of two buttons on same jsp is working fine.My issue is that I want to display chart on the same jsp from where i am making a call.Could you please suggest. – javaguy Oct 26 '14 at 18:09

1 Answers1

0

You can use AJAX. An example with jQuery:

<script>
    $(function(){
        $("#submitButton").click(function(e){
            e.preventDefault();
            $.ajax({type: "POST",
            url: "<s:url action='displayChartAction'/>",
            data: { 
                transactionBean.fromDate : $('[name="transactionBean.fromDate"]').val(‌​),
                transactionBean.toDate   : $('[name="transactionBean.toDate"]').val()
            },
            success:function(result){
                $("#chartOutput").html(result);
            }
        });
    });
</script>

<input type="button" id="submitButton" value="Show Chart" />

<div id="chartOutput"> 
    Click the button to load the chart here 
</div>

Alternatively, you can perform a GET and load the result in an IFrame on the page, by changing its src attribute to an URL with parameters...

These are the two most used ways.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • Thanks Andrea for your answer.I have never used Ajax before.Could you please let me know,if following code is required indeed in my case ,as execute method does not have any parameters to accept :data: { param1: $("#param1").val(), param2: $("#param2").val(), paramN: $("#paramN").val() }, – javaguy Oct 27 '14 at 21:58
  • Those are only example parameters in case you need to send something to the action. If you don't need to send anything, just remove the data part (and change POST to GET) – Andrea Ligios Oct 27 '14 at 22:49
  • Thanks Andrea.I have udated Jsp code in the original post with the code you shared.Unfortunately it is not working for me.Could you please suggst,if I am doing something wrong. – javaguy Oct 27 '14 at 23:20
  • Obviously, if you go with jQuery, you need to [import jQuery](http://jquery.com/download/). Let's try with a CDN in test (but remember to download and reference your local copy of the library before going to production), by putting `` in your head section (BEFORE the script where you use jQuery.ajax) – Andrea Ligios Oct 27 '14 at 23:32
  • Thanks Andrea again.I have updated JfreeChartAction.java above.I put in head section and run code again. Problem now is I am calling display method while loading transactionData.jsp,in which i am instantiating TransactionBean. Now on click of show chart button,I am accessing selected values and passing them to datbase layer to execute query based on the input parameters. But now I am getting all the selected values as null in execute method.I tried with both POST and GET,but in both cases in execute,I am getting null values. – javaguy Oct 28 '14 at 11:10
  • Dear Andera....Sorrry to disturb you again.But i am struggling with ajax syntax.I have used following syntaxes (1) data: {param1: $("transactionBean.fromDate").val(),param2: $("#transactionBean.toDate").val(),param3:$("#transactionBean.rightChannels").val(), param4: $("#transactionBean.rightTransTypes").val(), param5: $("#transactionBean.rightBics").val()(2) data: {param1: $("fromDate").val(),param2: $("#toDate").val(), param3: $("#rightChannels").val(), param4: $("#rightTransTypes").val(), param5: $("#rightBics").val() But I am getting selected values as null in execute method. – javaguy Oct 28 '14 at 17:17
  • Dude, you need to think a bit out of the box. You are sending Key-Value pairs. If your previous pair was, for example, key `fromDate` and its value as value, now you need to use `fromDate : $("transactionBean.fromDate").val()`. Param1, exactly as Value1, is a placeholder value, an example, and need to be substituted by your real name. Param = the name you were sending to the server (name attribute of your HTML object), value = its value, that you take with a selector. `$("#something").val()` means take the HTML object with `id="something"` and get its value... – Andrea Ligios Oct 28 '14 at 17:50
  • $(function({$("#submitButton").click(function(e){e.preventDefault();$.ajax({type: "POST",url: "",data:{fromDate:$("transactionBean.fromDate").val(),toDate:$("transactionBean.toDate").val(), rightChannels: $("transactionBean.rightChannels").val(), rightTransTypes: $("transactionBean.rightTransTypes").val(), rightBics: $("transactionBean.rightBics").val() },success:function(result){$("#chartOutput").html(result);}}); });});....still null..should I have id property for each of input field and then use it for getting values. – javaguy Oct 28 '14 at 20:13
  • You are using wrong selectors. If you want to target the name attribute, you need to use $('[name="transactionBean.something"]')... – Andrea Ligios Oct 28 '14 at 22:12
  • can you pls give one example in terms of my code,using one of my attribute. – javaguy Oct 29 '14 at 19:43
  • Edited with two parameters. Not sure about the other ones because they're not in your code. – Andrea Ligios Oct 29 '14 at 20:35
  • Anybody has any idea? – javaguy Nov 03 '14 at 13:12
  • Sorry for the late, but I've no time to dig this deeper right now; I strongly suggest you to try a different, small steps approach: create a single JSP, with a single Action, with all the settings to default; then try loading data (no param) into a div of the same page with AJAX. When it works, retry with a single parameter. When it works, retry with a couple of parameters inside a bean (like now). Each time you are stuck, read the official docs and if it still doesn't work, ask a *specific* question about a specific problem. This should be easy, but as it is now, it is become too broad, sorry – Andrea Ligios Nov 03 '14 at 13:29