Jason Barr
Jason Barr

Reputation: 23

Querying MySQL through Java, using Javascript

I have an HTML page with JavaScript currently set up and a MySQL server that I've already configured to be queried from Java through the NetBeans IDE. I am trying to somehow connect the Java/JavaScript to allow changes in the HTML elements based on returned data from MySQL. I've initially looked at servlets but they only seem to provide a new page or at least unable to pass MySQL data back to JavaScript and JavaScript doesn't appear to be able to directly query the database.

My Java classes already output the correct values in the IDE, but i'm lost at how to connect this to the actual HTML in any way. Can I use JavaScript to directly call a Java method? All components are currently locally hosted. I've searched through pages and pages of documentation but nothing seems the correct fit.

Thanks

Upvotes: 0

Views: 60

Answers (1)

Tod Harter
Tod Harter

Reputation: 536

OK, so you are really asking a question which has a number of possible solutions depending on your needs.

Essentially there are two basic approaches to this kind of thing. In one you would use something like a servelet (but probably something more sophisticated like JSP). You CAN pass data to Javascript this way, by constructing scripts embedded in the page which are JS data structures holding the data. Nowadays this sort of solution is less commonly used...

The OTHER solution is AJAX. Write a microservice that queries your database in Java and returns JSON containing the data you want to display. On the Javascript side you will call XMLHttpRequest (probably via some library, there are a lot of choices there), get the data back, and then render it (again you can do this using any of a WIDE array of techniques).

A third path, which is basically the JSON path above, would be to use something like React, which allows you to do pre-rendering. Then you serve up your web page using Node.js and set things up so that the first page load is rendered SERVER SIDE, so the user instantly gets a populated view, but any subsequent requests will go through XMLHttpRequest and be rendered client-side. If you follow directions given in quite a few examples of this kind of approach it should not be TOO hard to implement. The only downside is your content is now dynamic and needs to be served up via Node.js, entailing a bit more resources on that side initially, vs if you don't do prerendering the initial page view is a bit slower, but you can serve up your front end via static means (like S3 buckets or equivalent, which is fast and cheap).

The upshot of all this is, you do need to make some decisions about application architecture at this point. There is a LOT of tech out there aimed at exactly this type of scenario, so you could approach it using many different flavors of tools and libraries.

Upvotes: 1

Related Questions