tags:

views:

306

answers:

5

Hi Im new to Applets and I am trying to set up a login applet that connects to my mySQL database.... It shows in Netbeans but not when I load it.... Can someone have a look and give back any suggestions?

P.S.Do I need to place my file in Tomcat?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JApplet;

public class Login extends JApplet{


    static int i=0;
    static String Logged="";
    static int ID=0;
    double total=0.0;
    double Firsttotal=0.0,x1=0.0,y1=0.0;
    double weight=50.00;
    static int level=1,count=0;
    Connection con = null;
    Statement st = null;
    Statement st2 = null;
    ResultSet rs = null;
    double score=0.0,score1=0.0,score2=0.0,score3=0.0;
    double Game1=0.0,Game2=0.0,Game3=0.0;



private static final String text = "<html> <center><b><font size=+3>Brain</font></b><b><font size=+3>Game</font></b></center> </html>";
DataB db=new DataB();

JPanel jPanel1 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JLabel jLabel1 = new JLabel();
JPanel jPanel2 = new JPanel();
GridBagLayout gridBagLayout1 = new GridBagLayout();
JLabel jLabel2 = new JLabel();
JLabel jLabel3 = new JLabel();
JTextField loginTextField = new JTextField(20);
JPasswordField passwordTextField = new JPasswordField(20);
JPanel jPanel3 = new JPanel();
JButton registerButton = new JButton();
JButton enterButton = new JButton();
FlowLayout flowLayout1 = new FlowLayout();
static String logged="";
boolean fInBrowser = true;

public void init() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}

private void authenticate(String l){

    if (!(logged.equals(""))) {
        System.out.println("login successfull");
        showTreeView();
    } else {
        JOptionPane.showMessageDialog(this,"Incorrect login or password","Error",JOptionPane.ERROR_MESSAGE);
        loginTextField.setText("");
        passwordTextField.setText("");
        loginTextField.requestFocusInWindow();
    } 
}

private void login(ActionEvent e) {
String login = loginTextField.getText();
String password = new String(passwordTextField.getPassword());
//validate login and password here. validity will be done by sending login/password to the server

if (login.equals("") || password.equals("")){       
    JOptionPane.showMessageDialog(this,"Either of the following have not been entered:\n\n-UserName\n-PassWord\n-UserName And PassWord\n\n *Please fill in all fields*","Error",JOptionPane.ERROR_MESSAGE);
}else{
logged=loginit(login,password);
authenticate(logged);
}
}

public String loginit(String login,String password){

        Connection con ;
        Statement st1 = null;
        ResultSet rs1 = null;

        String url = "jdbc:mysql://localhost:3306/braingame"; //where 3306 is the port, localhost is address of DB, and mysql is name of the database you wanna use...

        try{

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        con = DriverManager.getConnection(url, "root", "admin");
        st1 = con.createStatement();
        if (login.equals("") && password.equals("")){
            Logged="";
        }else{
        rs1=st1.executeQuery("select user_id,level from players where name like '%"+ login +"%' and password like '%"+password+"%' ");

        if (rs1.next()) {
            ID=rs1.getInt("user_id"); 
            level=rs1.getInt("level");
            Logged="yes";
        }
        }

        if (con != null) con.close(); //same for st and rs...

        } 

        catch(Exception e){System.out.println(e.getMessage());}

        return Logged;

}


 public static void main (String[] args) {
    //
    int frame_width=450;
    int frame_height=300;

    // Create an instance of this applet an add to a frame.
    Login applet = new Login ();
    applet.fInBrowser = true;
    applet.init ();

    // Following anonymous class used to close window & exit program
    JFrame f = new JFrame ("Demo");
    f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    // Add applet to the frame
    f.getContentPane ().add ( applet);
    f.setSize (new Dimension (frame_width, frame_height));
    f.setVisible (true);
  } // main


private void jbInit() throws Exception {
jPanel1.setLayout(borderLayout1);
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setText(text);
jPanel2.setLayout(gridBagLayout1);
jLabel2.setText("Password:");
jLabel3.setText("Login:");
registerButton.setText("Register");

passwordTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {

    login(e);

}
});

loginTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
    login(e);

}
});

registerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
register(e);
}
});
enterButton.setText("Enter");

enterButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
login(e);
}
});

jPanel3.setLayout(flowLayout1);
flowLayout1.setAlignment(FlowLayout.RIGHT);
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.add(jLabel1, BorderLayout.NORTH);
jPanel1.add(jPanel2, BorderLayout.CENTER);
jPanel2.add(loginTextField, new GridBagConstraints(2, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 11, 0, 0), 0, 0));
jPanel2.add(jLabel2, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(11, 0, 0, 0), 0, 0));
jPanel2.add(passwordTextField, new GridBagConstraints(2, 2, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(11, 11, 0, 0), 0, 0));
jPanel2.add(jLabel3, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
jPanel1.add(jPanel3, BorderLayout.SOUTH);
jPanel3.add(enterButton, null);
jPanel3.add(registerButton, null);
}
}

HTML CODE:

<HTML>
<HEAD>
   <TITLE>Applet HTML Page</TITLE>
</HEAD>
<BODY>


<H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3>

<P>
<APPLET codebase="classes" code="Login.class" width=850 height=500></APPLET>
</P>

<HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT>
</BODY>
</HTML>
+2  A: 

You'll have to sign your JAR(s) in order to be able to access the database. Take a look here for a quick tutorial:

MrWiggles
I don't believe it's necessary to sign the applet if it connects to the host it was loaded from.
Michael Borgwardt
has to connect on the same port too (presumably port 80)
TofuBeer
A: 

As a FYI its not good practice to create applets that connect to databases across the internet due to having to open ports etc in firewalls.

Jimmy
+1  A: 

How do you try to "load it"? That's the part that's going wrong here, the applet's source code is irrelevant at this point.

It may indeed be necessary to put the applet and the HTML page that contains it in a webserver in order for it to be able to connect to the database due to the security restriction that applets are only allowed to connect to the server they're loaded from.

Also note that except for a learning exercise, an applet should never connect directly to a database because it's inherently unsafe. Whoever runs the applet can decompile it and get the DB user and password ("root" and "admin" in your case - heck, why decompile when you could just guess it right?). At that point, the users and passwords inside your DB become irrelevant, they can do anything the DB user can: read all data and log in as an arbitrary user at the very least, and probably change, add and delete data at will as well.

Edit What do you mean with "It shows the applet,but no connection"? Putting your .class and the HTML file in Tomcat's webapp-root is correct, and the .java file is not necessary.

Judging from the HTML code, it may be that all you have to do is to remove the codebase attribute of the APPLET tag - it would only be corret if the Java .class file were in a subdirectory named "classes".

Also, when you talk about what you "allocate in the string", that sounds strange. The JDBC URL has nothing to do with the HTML file's location in Tomcat.

As for security: where you put the method that connects to the database does not matter: the classes are all part of the applet as far as the browser is concerned.

Michael Borgwardt
Please look at my reply below..
I have just included the HTML -(JShow.html) which I pasted above,the class and the java...No connection!! It's wierd as it seems to work fine in Netbeans...Could there be any security with Vista..??
+1  A: 

@ Micheal: I loaded the html page JShow .html from the browser....It shows the applet,but no connection...

I put the files in a folder called braingame into Tomcat/Webapps/Root..Which is what I allocate in the string:

String url = "jdbc:mysql://localhost:3306/braingame";

This includes the html and the class file.

Do I need to include the java file as well?

About Security..I had initially had the connection within another class,and I just called a method from that class...Will that still be seen as not secure??

Is your DB installed in the same computer where your browser is? Also, can you take a look at your browser's Java console? We might find some useful info like a stacktrace in it.
Chry Cheng
Yes,DB is on my computer,running everything from one place. I tried checking out the console from the start option but it keeps zooming out!! Am I on the right track by placing files in Tomcat?
Applets can only connect back on the same port that they were loaded from (if you are using appletviewer it miught be different). If you want to connect on another port you have to sign the applet.
TofuBeer
Yes, but where you place the files in Tomcat matters. If you put the .html in braingame and the .class in braingame/classes then you're on the right track.How did you know that you have "no connection"?
Chry Cheng
A: 

String url = "jdbc:mysql://localhost:3306/braingame";

The applet runs in the client browser, so it needs to connect to the server URL using the IP address or host name which is visible from the client. Localhost in this case would be the client itself. So instead it should be

"jdbc:mysql://www.yourappletdomain.com:3306/braingame";

It will be neccessary to open the firewall for port 3306 too ...

mjustin