Display a simple username/password Dialog from an AppletTag(s): Security
NOTE: This way to authenticate a user is NOT secured at all since the required information is embedded in the Applet.
[MyApplet.java]
import java.awt.*; import java.net.*; public class MyApplet extends java.applet.Applet { public String username = ""; public String password = ""; public void init() { if (!login()) { try { getAppletContext().showDocument (new URL(getCodeBase()+"accessdenied.html"),"_top"); } catch (Exception e) {e.printStackTrace(); } } else { // here the username and password are OK } } public boolean login() { boolean userValid = false; MyLogin login = new MyLogin (new Frame("")); requestFocus(); if (login.id) { username = login.username.getText(); password = login.password.getText(); userValid = validateUser(username , password); System.out.println ("The password for " + username + " is " + (userValid?"valid":"invalid")); } else System.out.println ("Cancel was pressed."); login.dispose(); return userValid; } private boolean validateUser(String usr, String pwd) { // here you will code some logic to validate the username // password... for testing purpose : // username = java password = avaj return (usr.equals("java") && pwd.equals("avaj")); } }
import java.awt.*; import java.awt.event.*; public class MyLogin extends Dialog implements ActionListener { boolean id = false; Button ok,can; TextField username; TextField password; MyLogin(Frame frame){ super(frame, "Welcome", true); setLayout(new FlowLayout()); username = new TextField(15); password = new TextField(15); password.setEchoChar('*'); add(new Label("User :")); add(username); add(new Label("Password :")); add(password); addOKCancelPanel(); createFrame(); pack(); setVisible(true); } void addOKCancelPanel() { Panel p = new Panel(); p.setLayout(new FlowLayout()); createButtons( p ); add( p ); } void createButtons(Panel p) { p.add(ok = new Button("OK")); ok.addActionListener(this); p.add(can = new Button("Cancel")); can.addActionListener(this); } void createFrame() { Dimension d = getToolkit().getScreenSize(); setLocation(d.width/4,d.height/3); } public void actionPerformed(ActionEvent ae){ if(ae.getSource() == ok) { id = true; setVisible(false); } else if(ae.getSource() == can) { id = false; setVisible(false); } } }
[login.html]
<HTML><HEAD><BODY> <TABLE><TR><TD> <APPLET CODE=MyApplet.class WIDTH=300 HEIGHT=300> </APPLET></TABLE> NOTE: View the java console for infos about the login process </BODY></HEAD> </HMTL>
[accessdenied.html]
<HTML> access is denied </HMTL>