[Solved] Can a java program be the mediator between webpage javascript and a Database? [closed]


Yes, you can use server-side Java code as a mediator. Use JavaScript to POST data to an HttpServlet, via JavaScript’s XMLHttpRequest object. Then handle the data in your servlet.

Once you’ve done your DB business, you can send a “All done!” response back, to be handled by your JS.

I suggest reading up on the XMLHttpRequest object. Also, look into HttpServlet examples involving POSTed data.

Here’s a quick example:

JS (Works in IE9+)

var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function(data) {
  console.log(data);
};
xmlhttp.open("POST", "/servlet", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

Java

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    String fname = req.getParameter("fname");
    // db code here

    PrintWriter out = resp.getWriter();
    out.print("All done!");
  }
}

solved Can a java program be the mediator between webpage javascript and a Database? [closed]