java - POST vs JDBC
OK so here's the code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import j开发者_Python百科ava.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.
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.
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:
- 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).
- 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.
- 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.
- 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.
精彩评论