简体   繁体   中英

How to pass a javascript variable into java servlet doPost

I have a HTML table which is having drop down what i am doing is if user is clicking on any of dropdown i am storing the column name and the corresponding row( billdate ) in to a variable now what i want to do is to pass this variable into my java servelt doPost method and use that variable into the doGet to make another ajax call. i have searched alot for passing variable into java servlets from javascript but haven't got any good answer.

here is my javascript table code

<div id="tbl"></div>

<ul id="contextMenu" class="dropdown-menu" role="menu">
  <li><a href="#" class="link1">Report1</a></li>
  <li><a href="#" class="Link2">Report2</a></li>
</ul>
    var currentlyClickedPlace = "";
$(window).load(function() {
  $dropdown = $("#contextMenu");
  $(".actionButton").click(function() {
    //move dropdown menu
    $(this).after($dropdown);
    //update links
    $(this).dropdown();

    currentlyClickedOutlet = $(this).attr("data-place");
    currentlyClickedBilldate = $(this).attr("data-plac");
  });
  $(".link1").click(function(){

    console.log(currentlyClickedOutlet)
    console.log(currentlyClickedBilldate)
 //   here  i have to make two ajax call one to send currentlyClickedOutlet and currentlyClickedBilldate to the server i.e javaservlet doPost
  //  and another one to bind new html table into test div wchich will give me data based on clicked dropdown
    //call ajax and bind the data into test div
  });

});

data = [{
    "amount": 291589,
    "billdate": "2018-08-01",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 58337,
    "billdate": "2018-08-01",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 65970,
    "billdate": "2018-08-01",
    "outlet": "KOLAR"
  },
  {
    "amount": 296125,
    "billdate": "2018-08-02",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 56545,
    "billdate": "2018-08-02",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 72213,
    "billdate": "2018-08-02",
    "outlet": "KOLAR"
  },
  {
    "amount": 346605,
    "billdate": "2018-08-03",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 62459,
    "billdate": "2018-08-03",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 65248,
    "billdate": "2018-08-03",
    "outlet": "KOLAR"
  },
  {
    "amount": 518212,
    "billdate": "2018-08-04",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 104801,
    "billdate": "2018-08-04",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 138151,
    "billdate": "2018-08-04",
    "outlet": "KOLAR"
  },
  {
    "amount": 628358,
    "billdate": "2018-08-05",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 115223,
    "billdate": "2018-08-05",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 134107,
    "billdate": "2018-08-05",
    "outlet": "KOLAR"
  },
  {
    "amount": 177866,
    "billdate": "2018-08-06",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 66095,
    "billdate": "2018-08-06",
    "outlet": "KOLAR"
  },
  {
    "amount": 284069,
    "billdate": "2018-08-07",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 58789,
    "billdate": "2018-08-07",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 67886,
    "billdate": "2018-08-07",
    "outlet": "KOLAR"
  },
  {
    "amount": 313128,
    "billdate": "2018-08-08",
    "outlet": "JAYANAGAR"
  },
  {
    "amount": 59939,
    "billdate": "2018-08-08",
    "outlet": "MALLESHWARAM"
  },
  {
    "amount": 68558,
    "billdate": "2018-08-08",
    "outlet": "KOLAR"
  }
]

let formatData = function(data) {

  let billdates = [];
  let outlets = [];
  data.forEach(element => {
    if (billdates.indexOf(element.billdate) == -1) {
      billdates.push(element.billdate);
    }
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  return {
    data: data,
    billdates: billdates,
    outlets: outlets,

  };
};



let renderTable = function(data, divId, filterdata) {
  billdates = data.billdates;
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById(divId);
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "Bill___Date";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  let grandTotal = 0;
  let outletWiseTotal = {};
  th = document.createElement("th");
  th.innerHTML = "Total1";
  th.classList.add("text-center");
  headerRow.appendChild(th);

  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = element;
    th.classList.add("text-center");
    headerRow.appendChild(th);
    outletWiseTotal[element] = 0;
    data.forEach(el => {
      if (el.outlet == element) {
        outletWiseTotal[element] += parseInt(el.amount);
      }
    });
    grandTotal += outletWiseTotal[element];
  });


  thead.appendChild(headerRow);
  headerRow = document.createElement("tr");
  th = document.createElement("th");
  th.innerHTML = "Total";
  th.classList.add("text-center");

  headerRow.appendChild(th);

  outlets.forEach(element => {
    th = document.createElement("th");
    th.innerHTML = outletWiseTotal[element];
    th.classList.add("text-right"); 
    headerRow.appendChild(th);
  });

  th = document.createElement("th");
  th.innerHTML = grandTotal;
  th.classList.add("text-right"); // grand total

  headerRow.insertBefore(th, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody");

  billdates.forEach(element => {
    let row = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = element;
    row.appendChild(td);
    let total = 0;

    outlets.forEach(outlet => {
      let el = 0;
      data.forEach(d => {
        if (d.billdate == element && d.outlet == outlet) {
          total += parseInt(d.amount);
          el = d.amount;
        }
      });




      td = document.createElement("td");
      a = document.createElement("a");

      td.classList.add("text-right");
      td.classList.add("dropdown");
      a.classList.add("btn");
      a.classList.add("btn-default");
      a.classList.add("actionButton");

      a.setAttribute("data-place", outlet);
      a.setAttribute("data-plac", element);



      a.setAttribute("data-toggle", "dropdown");
      a.innerHTML = el;
      td.appendChild(a); 

      row.appendChild(td);




    });


    td = document.createElement("td");
    td.innerHTML = total;
    td.classList.add("text-right"); 

    row.insertBefore(td, row.children[1]);
    tbody.appendChild(row);

  });

  table.appendChild(tbody);

  tbl.innerHTML = "";
  tbl.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
let formatedData = formatData(data);
renderTable(formatedData, 'tbl', '');

so when ill get the values clicked into my dopost method i have to used that variables into my doGet to make another ajax call to show some new data into test div

i know how to declare a global attribute into servlet to use that variable anywhere in my application

like this getServletContext().setAttribute("DateAttribute", Date);

here is my javaservlet code

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {


    String Date=getServletContext().getAttribute("DateAttribute").toString(); // this how i will access Date and Outlet from dopost to doget
    String Outlet=getServletContext().getAttribute("OutletAttribute").toString();

    //will use here the value of Date and Outlet


    response.getWriter().append("Served at: ").append(request.getContextPath());
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String Date = request.getParameter("currentlyClickedBilldate");  //here i want that values from java script
    String Outlet = request.getParameter("currentlyClickedOutlet");  //here i want that values from java script


    getServletContext().setAttribute("DateAttribute", Date);  //this is how i will make Date and Outlet a global variables to access anywhere in my application
    getServletContext().setAttribute("OutletAttribute", Outlet);

    doGet(request, response);
}
  • I only want to know how can i pass a variable from java script to java servlet via ajax please help me out guys

here is the fiddle of my HTML table

fiddle

I have to make two ajax call one is to post data into servlet and other is to get data from servlet to render new table into test div and this two call will make on click of dropdown ie Report1 frist i want to post the data then after call that data via ajax from do get please anyOne out here help me out on this

You check below to understand how to send the data using AJAX to servlet

You can use data to send data to servlet and you can use query parameters using ? as well. See below examples.

Jquery-ajax-options

Please note http://localhost:8080/testpost varies depending on your application.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#id1").click(function(){
        var user = 'get-user-by-query-param';
        $.get("http://localhost:8080/testget?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId1").html(data);
        });
    });

    $("#id2").click(function(){
        var user = 'post-user-by-query-param';
        $.post("http://localhost:8080/testpost?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId2").html(data);
        });
    });


    $("#id3").click(function(){

        var user = 'get-user-by-sending-in-data';
        var data = {"name": user};
        $.get("http://localhost:8080/testget",data, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId3").html(data);
        });
    });


    $("#id4").click(function(){
        var user = 'post-user-by-sending-in-data';
        var data = {"name": user};
        $.post("http://localhost:8080/testpost",data, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId4").html(data);
        });
    });

      $("#id5").click(function(){
        var user = 'get-user-by-query-param';
        $.get("http://localhost:8080/testget?name="+user, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            $("#divId1").html(data);
            var postData = {'name':data}
            $.post("http://localhost:8080/testpost",postData, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);
            data
            $("#divId4").html(data);
        });
        });
    });
});
</script>
</head>
<body>

<button id="id1">GET with query param</button>
<div id="divId1"></div>
<button id="id2">POST with query param</button>
<div id="divId2"></div>
<button id="id3">GET with data</button>
<div id="divId3"></div>
<button id="id4">POST with data</button>
<div id="divId4"></div>

<button id="id5">POST and GET with data</button>
<div id="divId5"></div>

</body>
</html>

I feel it is better to use for chaining the calls.

https://api.jquery.com/promise/

Using promise to chain the calls:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){

      $("#id5").click(function(){
        var user = 'get-user-by-query-param';
        $.when( $.get( "http://localhost:8080/testget?name="+user ) ).done(function( data, textStatus, jqXHR ) {
            $("#divId5").html(data);
            var postData = {'name':data+' second input'}
            $.post("http://localhost:8080/testpost",postData, function(data, status){
            alert("Data: " + data + "\nStatus: " + status);

            $("#divId5").append("<br/>"+data);
        });
});

    });
});
</script>
</head>
<body>



<button id="id5">POST and GET with data</button>
<div id="divId5"></div>

</body>
</html>

The below is my controller classes using springMVC

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WelcomeController {



    @RequestMapping("/testpost" )
    @PostMapping
    @ResponseBody
    public String testPost(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        return name;
        //return "welcome"; //if you want to return jsp
    }

    @RequestMapping("/testget" )
    @PostMapping
    @ResponseBody
    public String testGet(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        return name;
        ///return "welcome";
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM