views:

36

answers:

2

OK so here's the code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class Main {
    public static void main(String[] args)  {
        try {
            URL my_url = new URL("http://www.viralpatel.net/blogs/");
            BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
            String strTemp = "";
            while(null != (strTemp = br.readLine())){
            System.out.println(strTemp);
        }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Using this method I can use POST and GET methods using PHP scripts. I can then use the PHP scripts to the MySQL database which in turn outputs back to the java applet. Is this possible? (and safer?)

Thanks.

+2  A: 

It is definitely possible to connect to an intermediate script. You can use apache http components for that purpose.

You shouldn't use JDBC from an applet to connect to remote database, because someone will read the credentials and "hack" your database.

If you want a better approach with a similar idea - make a REST API.

Bozho
I would rather use POST and GET requests to connect to my MYSQL database... that's good right?
Dan
You can't connect to MySQL via HTTP.
Bozho
+1  A: 

You have to have an intermediary between the applet and database. If you're already writing Java, I'd put a servlet in between. It can handle GET and POST requests, but there are other benefits as well:

  1. You can have some measure of security, because the servlet can ask for credentials and only allow authenticated users to access the database. You can even add role based security to allow authorized users to do certain things (e.g., only admins write to the database).
  2. You can bind and validate request parameters before passing them back to the database. Combine this with prepared statements and your database will be safer from SQL injection attacks.
  3. The servlet container maintains a thread pool and assigns one thread per incoming request. Your app will be able to accomodate more users than a simple client/server app, which is bound by # of connections.
  4. The servlet container can maintain a pool of database connections. This will help to make your app more responsive, because it spreads the cost of connection creation across all requests.
duffymo
Why can't I just have the PHP page do the mysql work and the java applet the display?
Dan