如何将请求从servlet doGet方法转发到新的html / jsp页面

时间:2018-08-22 05:38:40

标签: javascript html

我正在使用Java servlet和html创建图表js(条形图),我有一个具有两个日期字段和一个提交按钮的表单,单击该按钮可将我的操作前进到我要返回数据的servlet 以json的形式和我的新html中,有一个具有ajax调用的javascript,它正在调用MYServlet方法,但是当iam从用户传递日期时,日期值将为null,并且在html页面中显示任何内容我想在html页面上显示它们
以下是我的html表单

    Below is my html Form
         <form id="form Id" action="MyServlet"
                    method="get">
                    <div class="container">
                        <h4>Start Date:</h4>
                        <input type="text" id="startdate" name="fromdate" width="276"
                            placeholder="dd/mm/yyyy" required />
                        <h4>End Date:</h4>
                        <input type="text" id="enddate" name="todate" width="276"
                            placeholder="dd/mm/yyyy" required />
                        <div>
                            <br>
                            <button id="test" style="border-radius: 4px;" type="submit">Search</button>
                        </div>

                    </div>

                </form>


**below is my servlet whic is getting data from db an converting it to hson object to display chart in new html**

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String fromdate=request.getParameter("fromdate");
            String todate=request.getParameter("todate");

            String str = null;
            Gson gson = new Gson();
            Map<Object, Object> map = null;
            List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
            int xVal ,yVal,zVal,aVal,bVal;

            try {
                con = DBConnection.createConnection();
                statement = con.createStatement();
    String sql="select  sum(a.CASH) Cashamount,sum(a.CREDITCARD) Creditcardamount,sum(a.COUPONS) Couponamount,sum(a.CHEQUE) PAYTMamount,sum(a.CREDIT) Creditamount  from syncbill a  where  a.CANCELLED<>'Y' and a.billdate between '"+fromdate+"' and '"+todate+"'";
                ResultSet resultSet = statement.executeQuery(sql);
                while (resultSet.next()) {
                    map = new HashMap<Object, Object>();
                    xVal = resultSet.getInt("Cashamount");
                    map.put("CashamountX", "Cashamount");
                    map.put("CashamountY", xVal);

                    yVal = resultSet.getInt("Creditcardamount");
                    map.put("CreditcardamountX", "Creditcardamount");
                    map.put("CreditcardamountY", yVal);

                    zVal = resultSet.getInt("Couponamount");
                    map.put("CouponamountX", "Couponamount");
                    map.put("CouponamountY", zVal);

                    aVal = resultSet.getInt("PAYTMamount");
                    map.put("PAYTMamountX", "PAYTMamount");
                    map.put("PAYTMamountY", aVal);

                    bVal = resultSet.getInt("Creditamount");
                    map.put("CreditamountX", "Creditamount");
                    map.put("CreditamountY", bVal);

                    list.add(map);
                    str = gson.toJson(list);

                }

                response.setContentType("application/json");

                response.getWriter().write(str);

            } catch (SQLException e) {

                e.printStackTrace();
            }
        }

最后是我的具有图表和Java脚本的图表js html文件

<div id="chart-container">
        <canvas id="mycanvas"></canvas>
    </div>

<script>
        $(document).ready(
                function() {
                    $.ajax({
                        url : "MyServlet",
                        method : "GET",
                        success : function(data) {
                            var player = [];
                            var score = [];

                            for ( var i in data) {
                                player.push(data[i].CashamountX);
                                score.push(data[i].CashamountY);

                                player.push(data[i].CreditcardamountX);
                                score.push(data[i].CreditcardamountY);

                                player.push(data[i].CouponamountX);
                                score.push(data[i].CouponamountY);

                                player.push(data[i].PAYTMamountX);
                                score.push(data[i].PAYTMamountY);

                                player.push(data[i].CreditamountX);
                                score.push(data[i].CreditamountY);
                            }
                            var chartdata = {
                                labels : player,
                                datasets : [ {
                                    label : 'Amount',
                                    backgroundColor : [ '#6495ED', '#FFF8DC',
                                            '#008B8B', '#DCDCDC', '#E6E6FA' ],
                                    borderColor : 'black',
                                    hoverBackgroundColor : '#B0C4DE',
                                    hoverBorderColor : 'red',
                                    data : score
                                } ]
                            };

                            var ctx = $("#mycanvas");

                            var barGraph = new Chart(ctx, {
                                type : 'bar',
                                data : chartdata
                            });
                        },
                        error : function(data) {

                        }
                    });
                });
    </script>

2 个答案:

答案 0 :(得分:0)

您必须在表单的Submit事件上调用Ajax函数。就像下面一样,

$(document).ready(function(){ 
    $("#form_id").submit(function(event){ // don't put space in id or name in HTML
        event.preventDefault(); // to stop form being submitted because it reloads the page.
        $.ajax({
            url : "MyServlet",
            method : "GET",
            data : {
                fromdate : $("#startdate").val(),
                todate : $("#enddate").val()
            }, 
            success : function(data) {
                // your success function
            }
        });
    });
});

在这里,您的表单,画布和脚本必须位于同一文件中。并且您也可以从表单中省略action="MyServlet"属性。

编辑::这是程序的完整代码

<html>
<body>
<form id="form_id" method="get">
    <div class="container">
        <h4>Start Date:</h4>
        <input type="text" id="startdate" name="fromdate" width="276" placeholder="dd/mm/yyyy" required />
        <h4>End Date:</h4>
        <input type="text" id="enddate" name="todate" width="276" placeholder="dd/mm/yyyy" required />
        <div>
            <br>
            <button id="test" style="border-radius: 4px;" type="submit">Search</button>
        </div>
    </div>
</form>

<div id="chart-container">
    <canvas id="mycanvas"></canvas>
</div>

<script>
    $(document).ready(function(){ 
        $("#form_id").submit(function(event){ // don't put space in id or name in HTML
            event.preventDefault(); // to stop form being submitted because it reloads the page.
        $.ajax({
            url : "MyServlet",
            method : "GET",
            data : {
                fromdate : $("#startdate").val(), // my bad it's val not value.
                todate : $("#enddate").val()
            }, 
            success : function(data) {
                $("#form_id").hide(); // this will hide the form.
                var player = [];
                var score = [];
                for ( var i in data) {
                    player.push(data[i].CashamountX);
                    score.push(data[i].CashamountY);
                    
                    player.push(data[i].CreditcardamountX);
                    score.push(data[i].CreditcardamountY);
                    
                    player.push(data[i].CouponamountX);
                    score.push(data[i].CouponamountY);

                    player.push(data[i].PAYTMamountX);
                    score.push(data[i].PAYTMamountY);

                    player.push(data[i].CreditamountX);
                    score.push(data[i].CreditamountY);
                }
                var chartdata = {
                    labels : player,
                    datasets : [ {
                        label : 'Amount',
                        backgroundColor : [ '#6495ED', '#FFF8DC',
                            '#008B8B', '#DCDCDC', '#E6E6FA' ],
                        borderColor : 'black',
                        hoverBackgroundColor : '#B0C4DE',
                        hoverBorderColor : 'red',
                        data : score
                    }]
                };

                var ctx = $("#mycanvas");

                var barGraph = new Chart(ctx, {
                    type : 'bar',
                    data : chartdata
                });
            }
        });
    });
});
</script>
</body>
</html>

答案 1 :(得分:0)

尝试:

HashMap >>列表=新的HashMap <>();         list.put(“ data”,allData);

    Gson gson = new Gson();
    String json = gson.toJson(list);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);