Vous êtes sur la page 1sur 81

ENSICAEN

6, bd maréchal Juin
F-14050 Caen cedex 4

Spécialité Informatique - 2e année


Compte-rendu du TP JAVA

Programmation JAVA

Younes EL KHATTAB
Mohamed LAHLOU

Suivi Ensicaen : Patrick DUCROT

2007-2008
Table des matières

TP1 : Sockets et RMI ............................................................................................................................... 3


1.1 Programmation sockets .............................................................................................................. 3
1.1.1 Code JAVA .......................................................................................................................... 3
1.1.2 Exemple d’exécution ............................................................................................................ 5
1.2 Programmation RMI ................................................................................................................... 7
1.2.1 Serveur horaire ..................................................................................................................... 7
1.2.1.1 Code JAVA.................................................................................................................... 7
1.2.1.2 Remarques ..................................................................................................................... 8
1.2.2 Développement d’un logiciel de discussion ......................................................................... 9
1.2.2.1 JAVADOC..................................................................................................................... 9
1.2.2.1 Code Java..................................................................................................................... 15
1.2.2.2 Exemple d’exécution ................................................................................................... 25
2 TP2 :JavaBeans................................................................................................................................ 26
2.1 Code Source : ............................................................................................................................ 26
2.2 Exemple d’exécusion ................................................................................................................ 32
3 TP3 : Interaction Java-Base de données .......................................................................................... 34
3.1 Première partie : ........................................................................................................................ 34
3.1.1 JAVADOC ......................................................................................................................... 34
3.1.2 CODE JAVA ...................................................................................................................... 38
3.1.3 Exemple D’exécusion : ...................................................................................................... 45
3.2 Deuxième partie ........................................................................................................................ 46
3.2.1 CODE JAVA ...................................................................................................................... 46
3.2.2 Exemple d’exécusion ......................................................................................................... 48
4 TP4 : Programmation JSP................................................................................................................ 49
4.1 Exercice 1.................................................................................................................................. 49
4.1.1 JAVADOC : ....................................................................................................................... 49
4.1.2 Code JAVA ........................................................................................................................ 51
4.1.3 Exemple d’exécution .......................................................................................................... 53
4.2 Exercice 2.................................................................................................................................. 54
4.2.1 JAVADOC ......................................................................................................................... 54
4.2.2 CODE JAVA ...................................................................................................................... 57
4.2.3 Exemple d’exécution .......................................................................................................... 73
4.2.3.1 Enregistrement ............................................................................................................. 73
4.2.3.2 Connexion.................................................................................................................... 76
4.2.3.3 Récupération de mot passe (JAVAMAIL) : ................................................................ 78
5 Conclusion ....................................................................................................................................... 81
TP1 : Sockets et RMI
1.1 Programmation sockets
Dans ce premier exercice, l’objectif est de lister le contenu d’un répertoire distant en utilisant des
sockets. Du coté serveur, le traitement s’effectue dans un thread.

1.1.1 Code JAVA

server.java
import java.net.*;
import java.io.*;

public class server {

public static void main(String args[]) throws IOException


{
ServerSocket s= null;
lister l;

try{
s=new ServerSocket(45225);
}catch(IOException e)
{
System.err.println("Erreur socket" +e);
System.exit(1);
}
while(true)
{
Socket service= s.accept();
l=new lister(service);
l.start();
}
}

class lister extends Thread{

private Socket service;


private PrintStream flux;
private String listning[];
private BufferedReader requete;

public lister(Socket service){


this.service=service;
}

public void run()


{
try {
requete = new BufferedReader (new
InputStreamReader(service.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

3
try {
flux=new PrintStream(service.getOutputStream(),true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
File f= new File(requete.readLine());
listning=new String[f.list().length];
listning=f.list();
flux.println(listning.length);
for(int i=0;i<listning.length;i++)
flux.println(listning[i]);
}catch(IOException e)
{
flux.println(-1);//dans le cas ou l'adresse demandée n'existe
pas
}
}
}

client.java
import java.net.*;
import java.io.*;
import javax.swing.JOptionPane;

public class client {


public static void main(String args[]) throws IOException{
Socket s=null;
PrintStream flux=null;
int nbEntree;
try{
s=new Socket("PC86",45225);
}catch (IOException e)
{
System.err.println("La connexion a echoué");
System.exit(1);
}
flux = new PrintStream(s.getOutputStream(),true);
flux.println(JOptionPane.showInputDialog("Entrer l'adresse du
repertoire à lister"));
BufferedReader reponse = new BufferedReader(new InputStreamReader
(s.getInputStream()));
nbEntree=Integer.parseInt(reponse.readLine());
if(nbEntree<0){
System.out.println("L'adreese est incorrecte");
System.exit(-1);
}
System.out.println("le nombre d'entrées dans le repertoire est:
"+nbEntree+"\nLes entrées sont:");
for(int i=0;i<nbEntree;i++)
{
System.out.println(reponse.readLine());
}
}
}

4
1.1.2 Exemple d’exécution

Capture d’écran lors de l’exécution

Dans cet exemple, le client cherche à lister le repértoire C: . Après cette requête, le message
affiché dans la console est :
Console :
le nombre d'entrées dans le repertoire est: 26
Les entrées sont:
arcldr.exe
arcsetup.exe
AUTOEXEC.BAT
BOOT.BAK
boot.ini
Bootfont.bin
cmdcons
cmldr
CONFIG.SYS

5
Documents and Settings
eclipse
IO.SYS
JBuilder4
JBuilder9
MC7DEMO
MSDOS.SYS
NTDETECT.COM
ntldr
ocs-ng
pagefile.sys
Program Files
Qt
RECYCLER
System Volume Information
temp
WINNT

6
1.2 Programmation RMI

1.2.1 Serveur horaire


Dans cet exercice, l’objectif est de développer un serveur capable d’envoyer la date et l’heure
en utilisant les RMI.

1.2.1.1 Code JAVA

InterfaceHeureServeur.java
import java.rmi.*;

public interface InterfaceHeureServeur extends Remote{

public String getHeure() throws RemoteException;


}

serInterface.java
import java.net.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.*;

public class serInterface extends UnicastRemoteObject implements


InterfaceHeureServeur{

public serInterface() throws RemoteException{ super();}


public String getHeure() throws RemoteException {
Date date=new Date();
return ("Voici la date du serveur" + date);
}

public static void main(String args[]){


try{
serInterface h=new serInterface();
System.setSecurityManager(new
java.rmi.RMISecurityManager());
LocateRegistry.createRegistry(25123);
Naming.rebind("//pc31/myObject",h);
System.out.println("Serveur pret");
}catch(RemoteException e){
System.err.println("RemoteException "+e);
}
catch(MalformedURLException
e){System.err.println("MalformedURLException "+e);}
}
}

7
client.java :
import java.rmi.*;

public class client {


public static void main (String args[]){

System.setSecurityManager(new java.rmi.RMISecurityManager());
try{
InterfaceHeureServeur h = ( InterfaceHeureServeur )
Naming.lookup("rmi://pc31/myObject");
System.out.println(h.getHeure());
}catch(Exception e){
System.err.println("Exception: "+e);
}
}
}

1.2.1.2 Remarques

Nous avons compilé client et serveur dans 2 répertoires différents, en conséquence, le client
n’as pas pu trouvé le _Stub.class et _Skel.class . Nous avons dû les déplacer dans le serveur
(public_html) et ajouter le port 80 dans le fichier .policy et indiquer l’adresse url au client lors de
l’exécution pour les trouver.

8
1.2.2 Développement d’un logiciel de discussion
Dans cette partie, il s’agit de développer un logiciel de discussion en direct en utilisant les RMI.
L’interface utilisateur est réalisé avec le plugin ‘‘jigloo’’.

1.2.2.1 JAVADOC

Class ChatServeur
java.lang.Object
java.rmi.server.RemoteObject
java.rmi.server.RemoteServer
java.rmi.server.UnicastRemoteObject
ChatServeur
All Implemented Interfaces:
InterfaceChatServeur, java.io.Serializable, java.rmi.Remote

public class ChatServeur


extends java.rmi.server.UnicastRemoteObject
implements InterfaceChatServeur
This class used to expose the server and look up for the client.
Author:
khattab
See Also:
Serialized Form

Constructor Summary
ChatServeur()

Method Summary
void broadcastMessage(Message msg)
This method send a message entered as an argument to all connected
clients.
java.lang.String connect(java.lang.String pseudo, java.lang.String url)
adds the pseudo and URL entered as an argument into the set clients.
void disconnect(java.lang.String pseudo)
Remove the client from the set.
java.util.Calendar getCalendar()
return a Calendar object to indicate the server's time.
static void main(java.lang.String[] args)

9
Methods inherited from class java.rmi.server.UnicastRemoteObject
clone, exportObject, exportObject, exportObject, unexportObject

Methods inherited from class java.rmi.server.RemoteServer


getClientHost, getLog, setLog

Methods inherited from class java.rmi.server.RemoteObject


equals, getRef, hashCode, toString, toStub

Methods inherited from class java.lang.Object


getClass, notify, notifyAll, wait, wait, wait

Constructor Detail
ChatServeur
public ChatServeur()
throws java.rmi.RemoteException
Throws:
java.rmi.RemoteException

Method Detail
getCalendar
public java.util.Calendar getCalendar()
throws java.rmi.RemoteException
Description copied from interface: InterfaceChatServeur
return a Calendar object to indicate the server's time.
Specified by:
getCalendar in interface InterfaceChatServeur
Returns:
Calendar.
Throws:
java.rmi.RemoteException

connect
public java.lang.String connect(java.lang.String pseudo,
java.lang.String url)
throws java.rmi.RemoteException
Description copied from interface: InterfaceChatServeur
adds the pseudo and URL entered as an argument into the set clients.
Specified by:
connect in interface InterfaceChatServeur
Returns:
String specify if the clients is added or not, and why not if is the.
Throws:

10
java.rmi.RemoteException

disconnect
public void disconnect(java.lang.String pseudo)
throws java.rmi.RemoteException
Description copied from interface: InterfaceChatServeur
Remove the client from the set.
Specified by:
disconnect in interface InterfaceChatServeur
Throws:
java.rmi.RemoteException

broadcastMessage
public void broadcastMessage(Message msg)
throws java.rmi.RemoteException
Description copied from interface: InterfaceChatServeur
This method send a message entered as an argument to all connected clients.
Specified by:
broadcastMessage in interface InterfaceChatServeur
Parameters:
msg - Message to be sent.
Throws:
java.rmi.RemoteException

main
public static void main(java.lang.String[] args)

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

11
Package Class Use Tree Deprecated Index Help
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Class ChatClient
java.lang.Object
java.rmi.server.RemoteObject
java.rmi.server.RemoteServer
java.rmi.server.UnicastRemoteObject
ChatClient
All Implemented Interfaces:
InterfaceChatClient, java.io.Serializable, java.rmi.Remote

public class ChatClient


extends java.rmi.server.UnicastRemoteObject
implements InterfaceChatClient
This class used to expose the client and look up for the server.
Author:
khattab
See Also:
Serialized Form

Method Summary
void connexion(java.lang.String nickName, ChatClient b)

void deconexion()

void diffuseMessage(Message msg)


display the message entered as an argument.
java.util.Calendar getCalendar()

static void main(java.lang.String[] args)

void sendMsg(java.lang.String Msg)

Methods inherited from class java.rmi.server.UnicastRemoteObject


clone, exportObject, exportObject, exportObject, unexportObject

Methods inherited from class java.rmi.server.RemoteServer


getClientHost, getLog, setLog

12
Methods inherited from class java.rmi.server.RemoteObject
equals, getRef, hashCode, toString, toStub

Methods inherited from class java.lang.Object


getClass, notify, notifyAll, wait, wait, wait

Method Detail
diffuseMessage
public void diffuseMessage(Message msg)
throws java.rmi.RemoteException
Description copied from interface: InterfaceChatClient
display the message entered as an argument.
Specified by:
diffuseMessage in interface InterfaceChatClient
Throws:
java.rmi.RemoteException

connexion
public void connexion(java.lang.String nickName,
ChatClient b)
throws java.net.MalformedURLException,
java.rmi.RemoteException,
java.rmi.NotBoundException
Throws:
java.net.MalformedURLException
java.rmi.RemoteException
java.rmi.NotBoundException

deconexion
public void deconexion()
throws java.net.MalformedURLException,
java.rmi.RemoteException,
java.rmi.NotBoundException
Throws:
java.net.MalformedURLException
java.rmi.RemoteException
java.rmi.NotBoundException

sendMsg
public void sendMsg(java.lang.String Msg)
throws java.net.MalformedURLException,
java.rmi.RemoteException,
java.rmi.NotBoundException
Throws:
java.net.MalformedURLException
java.rmi.RemoteException
java.rmi.NotBoundException

getCalendar
public java.util.Calendar getCalendar()

13
throws java.rmi.RemoteException
Throws:
java.rmi.RemoteException

main
public static void main(java.lang.String[] args)

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

14
1.2.2.2 Code Java

Message.java
import java.io.Serializable;

public class Message implements Serializable {


private String msg;
private String pseudo;

public Message(String pseudo, String msg)


{
this.pseudo=pseudo;
this.msg=msg;
}

public String getMessage(){return msg;}


public String getPseudo(){return pseudo;}
}

EnsConnect.java
public class EnsConnect {
private int nbConnect;
private String pseudo[];
private String url[];
private int maxConnect;

/**
* Create a set of clients.
* @param maxConnect, the set's maximal size.
*/
public EnsConnect(int maxConnect){
this.maxConnect=maxConnect;
this.nbConnect=0;
pseudo=new String[maxConnect];
url=new String[maxConnect];
}

/**
* Adds a client to the set.
* @param pseudo
* @param url
* @return -1 if the pseudo is already exist.
* 0 if the number of clients is maximal.
* 1 if the client is added.
*/
public int addConnect(String pseudo, String url)
{
for(int i=0;i<nbConnect;i++){
if(this.pseudo[i].compareToIgnoreCase(pseudo)==0)
return -1;
}
if(nbConnect==maxConnect)

15
return 0;
{
this.pseudo[nbConnect]=pseudo;
this.url[nbConnect]=url;
nbConnect++;
return 1;
}
}
/**
* Remove the client specified in the argument from the set.
* @param pseudo
*/
public void subConnect(String pseudo)
{
for(int i=0;i<nbConnect;i++)
if(pseudo.compareToIgnoreCase(this.pseudo[i])==0)
{
this.pseudo[i]=this.pseudo[nbConnect-1];
this.url[i]=this.url[nbConnect-1];
nbConnect--;
}
}

/**
* Return the number of clients.
* @return the number of clients.
*/
public int getNbConnect(){return this.nbConnect;}

/**
* Return the URL of client.
* @param i, the index of client.
* @return the URL of client.
*/
public String getConnectUrl(int i){return url[i];}

/**
* Return the pseudo of client.
* @param i, the index of client.
* @return the Pseudo of client.
*/
public String getConnectPseudo(int i){return pseudo[i];}
}

InterfaceChatServeur.java
import java.rmi.*;
import java.util.Calendar;
import java.util.Date;
/**
* This interface used to expose the server and look up for the client.
* @author khattab
*/

public interface InterfaceChatServeur extends Remote{

/**
* adds the pseudo and URL entered as an argument into the set clients.

16
* @param pseudo
* @param url
* @return String specify if the clients is added or not, and why not if is
the.
* @throws RemoteException
*/
public String connect(String pseudo, String url) throws RemoteException;

/**
* Remove the client from the set.
* @param pseudo
* @throws RemoteException
*/
public void disconnect(String pseudo) throws RemoteException;

/**
* This method send a message entered as an argument to all connected
clients.
* @param msg Message to be sent.
* @throws RemoteException
*/
public void broadcastMessage(Message msg) throws RemoteException;

/**
* return a Calendar object to indicate the server's time.
* @return Calendar.
* @throws RemoteException
*/

public Calendar getCalendar() throws RemoteException;


}

ChatServeur.java
import java.net.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import java.util.Calendar;
import java.util.Date;

/**
* This class used to expose the server and look up for the client.
* @author khattab
*/

public class ChatServeur extends UnicastRemoteObject implements


InterfaceChatServeur{

private EnsConnect C =new EnsConnect(20);


public ChatServeur() throws RemoteException{ super();}

public Calendar getCalendar() throws RemoteException{


return Calendar.getInstance();
}

public String connect(String pseudo, String url) throws


RemoteException {
int etat=C.addConnect(pseudo, url);

17
if(etat==-1)
return "Ce pseudo est deja connecté, veuillez vous
connecter avec un auter pseudo";
if(etat==0)
return "Le chat Romm est pleine. Veuillez vous reconnecter
ultérieurement";
return "Connecxion établie";
}

public void disconnect(String pseudo) throws RemoteException{


C.subConnect(pseudo);
}

public void broadcastMessage(Message msg) throws RemoteException{


for(int i=0;i<C.getNbConnect();i++)
{
try{
InterfaceChatClient h = ( InterfaceChatClient )
Naming.lookup("rmi://"+C.getConnectUrl(i)+"/"+C.getConnectPseudo(i));
h.diffuseMessage(msg);
}catch(Exception e){
System.err.println("Exception: "+e);
}
}
}

public static void main(String args[]){


try{
ChatServeur h=new ChatServeur();
System.setSecurityManager(new
java.rmi.RMISecurityManager());
//LocateRegistry.createRegistry(25123);
Naming.rebind("myObject",h);
System.out.println("Serveur pret");
}catch(RemoteException e){
System.err.println("RemoteException "+e);
}
catch(MalformedURLException
e){System.err.println("MalformedURLException "+e);}
}
}

InterfaceChatClient.java
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
*
* This interface used to expose the client and look up for the server.
* @author khattab
*/
public interface InterfaceChatClient extends Remote{
/**
* display the message entered as an argument.
*
* @param msg.
* @throws RemoteException
*/
public void diffuseMessage(Message msg) throws RemoteException;
}

18
ChatClien.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.util.Calendar;
import java.net.*;

import javax.swing.JOptionPane;

/**
*
* This class used to expose the client and look up for the server.
* @author khattab
*/

public class ChatClient extends UnicastRemoteObject implements InterfaceChatClient


{
static Display d;
private int etatConnexion=0;
private static String url;
private static String Pseudo;
InterfaceChatServeur h;

protected ChatClient() throws RemoteException {


super();
d=new Display(this);
}

public void diffuseMessage(Message msg) throws RemoteException {


d.addMsg(msg.getPseudo()+":\t"+msg.getMessage());
}

public void connexion(String nickName, ChatClient b) throws


MalformedURLException, RemoteException, NotBoundException{
//LocateRegistry.createRegistry(25123);
Pseudo=nickName;
Naming.rebind(Pseudo,b);
System.out.println("Interface client est prete");

//Detect server interface.


h = ( InterfaceChatServeur )
Naming.lookup("rmi://PC0/myObject");
d.addMsg(h.connect(Pseudo,url)+"\n");
h.broadcastMessage(new Message(Pseudo,"s'est connecté(e)"));
etatConnexion=1;
}

public void deconexion() throws MalformedURLException, RemoteException,


NotBoundException{
h.broadcastMessage(new Message(Pseudo, "s'est deconnecté(e)"));
h.disconnect(Pseudo);
etatConnexion=0;
}

public void sendMsg(String Msg) throws MalformedURLException,


RemoteException, NotBoundException{
h.broadcastMessage(new Message(Pseudo,Msg));
}

19
public Calendar getCalendar() throws RemoteException{
if(etatConnexion==1)
return h.getCalendar();
return null;
}

public static void main (String args[]){

url=args[0];
Time t;
System.setSecurityManager(new java.rmi.RMISecurityManager());
try {
ChatClient b=new ChatClient();
t=new Time(b);
t.start();
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

Display.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Display extends javax.swing.JFrame {

{
try {
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.get
SystemLookAndFeelClassName());
} catch(Exception e) {

20
e.printStackTrace();
}
}

private JTextPane P;
private JTextPane time1;
private JTextPane time2;
private JButton Connect;
private JButton disConnect;
private JTextArea Msg;
private JTextField Saisie;
private JTextPane TimeServeur;
private JTextPane TimeClient;
private JTextField Pseudo;
private ChatClient b;

public void affiche(final Display d) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
d.setLocationRelativeTo(null);
d.setVisible(true);
}
});
}

public void addMsg(String msg){


Msg.append(msg+"\n");
}
public Display(ChatClient b) {
super("Chat");
initGUI();
affiche(this);
this.b=b;
}

public void setTimeClient(int heure,int min, int second){


TimeClient.setText(heure+":"+min+ ":" +second);
}

public void setTimeServeur(int heure,int min, int second){


TimeServeur.setText(heure+":"+min+":"+second);
}

private void initGUI() {


try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
this.setPreferredSize(new java.awt.Dimension(730, 489));
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
try{
Deconexion();
}catch(Exception e1){
super.windowClosing(e);

21
System.exit(1);
}
super.windowClosing(e);
System.exit(0);
}
}
);
{
P = new JTextPane();
getContentPane().add(P);
P.setText("Pseudo");
P.setBounds(12, 7, 66, 27);
P.setOpaque(false);
P.setFocusable(false);
}
{
Pseudo = new JTextField();
getContentPane().add(Pseudo);
Pseudo.setBounds(76, 7, 123, 27);
}
{
time1 = new JTextPane();
getContentPane().add(time1);
time1.setText("Heure Client");
time1.setBounds(339, 11, 84, 27);
time1.setOpaque(false);
time1.setFocusable(false);
}
{
TimeClient = new JTextPane();
getContentPane().add(TimeClient);
TimeClient.setBounds(416, 10, 71, 27);
TimeClient.setOpaque(false);
TimeClient.setFocusable(false);
}
{
time2 = new JTextPane();
getContentPane().add(time2);
time2.setText("Heure Serveur");
time2.setBounds(508, 11, 101, 27);
time2.setOpaque(false);
time2.setFocusable(false);
}
{
TimeServeur = new JTextPane();
getContentPane().add(TimeServeur);
TimeServeur.setBounds(619, 11, 63, 22);
TimeServeur.setOpaque(false);
TimeServeur.setFocusable(false);
}
{
Saisie = new JTextField();
Saisie.setBounds(0, 390, 714, 33);
getContentPane().add(Saisie);
}
{
Msg = new JTextArea();
Msg.setBounds(0, 49, 714, 330);
Msg.setFocusable(false);
getContentPane().add(Msg);
}

22
{
Connect = new JButton();
getContentPane().add(Connect);
Connect.setText("Connexion");
Connect.setBounds(205, 7, 113, 27);
}
{
disConnect = new JButton();
getContentPane().add(disConnect);
disConnect.setText("Deconexion");
disConnect.setBounds(205, 7, 113, 27);
disConnect.setVisible(false);
}
gestionEvent gestionnaire =new gestionEvent();
Connect.addActionListener(gestionnaire);
disConnect.addActionListener(gestionnaire);
Saisie.addActionListener(gestionnaire);
pack();
this.setSize(730, 489);
} catch (Exception e) {
e.printStackTrace();
}
}

private void SaisieMsg(String Msg){


try {
b.sendMsg(Msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}

private void Connexion(String Pseudo){


try {
b.connexion(Pseudo, b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}

private void Deconexion(){


try {
b.deconexion();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}

23
private class gestionEvent implements ActionListener{
public void actionPerformed (ActionEvent e){
if(e.getSource()==Connect){
Connexion(Pseudo.getText());
Connect.setVisible(false);
disConnect.setVisible(true);
}
if(e.getSource()==Saisie){
SaisieMsg(Saisie.getText());
Saisie.setText("");
}
if(e.getSource()==disConnect){
Deconexion();
Msg.setText("");
disConnect.setVisible(false);
Connect.setVisible(true);
TimeServeur.setText("");
}
}
}

Time.java
import java.rmi.RemoteException;
import java.util.*;

public class Time extends Thread{


private Calendar cClient;
private Calendar cServer;
private ChatClient b;

public Time(ChatClient b) {
this.b=b;
}
public void run(){
while(true){
cClient=Calendar.getInstance();
ChatClient.d.setTimeClient(cClient.get(Calendar.HOUR_OF_DAY),
cClient.get(Calendar.MINUTE), cClient.get(Calendar.SECOND));
try {
cServer=b.getCalendar();
if(cServer!=null)

ChatClient.d.setTimeServeur(cServer.get(Calendar.HOUR_OF_DAY),
cServer.get(Calendar.MINUTE), cServer.get(Calendar.SECOND));
} catch (RemoteException e1){}

try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

24
1.2.2.3 Exemple d’exécution

25
2 TP2 :JavaBeans
Dans cet exercice, on va présenter que la version finale du bean, puisque c’est cette dernière qui
contient le maximum de propriétés. Vous trouverez les autres beans dans le CD accompagné avec ce
compte-rendu.

2.1 Code Source :

BeanAffichage2.java
import java.awt.*;
import java.io.*;

class Filter implements FilenameFilter{

public boolean accept(File arg0, String arg1) {

if(arg0.isDirectory()==true){
if(arg1.endsWith("jpg") || arg1.endsWith("gif")){
return true;
}
return false;
}
return false;
}

public class BeanAffichage2 extends Canvas implements Serializable, Runnable


{
private String dirName;
private Image [] imgs;
private int numImg;
private Filter f;
private int largeur=300;
private int longueur=240;
private boolean boucle;
private boolean diapo;
private int wait;

public BeanAffichage2()
{
numImg = 0;
dirName = "C:/images/";
boucle=false;
diapo=false;
wait=3;
f = new Filter();

File dir = new File(dirName);


if(dir.isDirectory())
{
String [] files = dir.list(f);

26
if(files.length != 0)
{
imgs = new Image [files.length];
for(int i=0; i<files.length; ++i)
imgs[i] =
Toolkit.getDefaultToolkit().getImage(dirName+files[i]);
}
}
}

public void setDir(String Dir){


numImg = 0;
dirName = Dir;
f = new Filter();

File dir = new File(dirName);


if(dir.isDirectory())
{
String [] files = dir.list(f);

if(files.length != 0)
{
imgs = new Image [files.length];
for(int i=0; i<files.length; ++i)
imgs[i] =
Toolkit.getDefaultToolkit().getImage(dirName+files[i]);
}
}
}

public void premier()


{
numImg = 0;
repaint();
}

public void dernier()


{
numImg = imgs.length-1;
repaint();
}

public void suivant()


{
numImg = (numImg+1) % imgs.length;
repaint();
}

public void precedent()


{
numImg--;
if(numImg == -1)
numImg = imgs.length-1;
repaint();
}

public void paint(Graphics g)


{
g.drawImage(imgs[numImg],0,0,largeur,longueur,this);

27
}
public Dimension getPreferredSize()
{
return new Dimension(largeur,longueur);
}

void setDiapo(boolean b){


diapo=b;
}

void setBoucle(boolean b){


boucle=b;
}

void setTempo(int tempo){


wait=tempo;
}

public void run() {


while(true){
try {
Thread.currentThread().sleep(wait*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(diapo==true){
if(boucle==true || (numImg<(imgs.length-1)))
suivant();
}
}

}
}

BeanHeure.java
import java.awt.*;
import java.util.Calendar;
import javax.swing.*;

public class BeanHeure extends JLabel{

private Calendar c;

public BeanHeure(){
upDate();
}

public void upDate(){


c=Calendar.getInstance();
this.setText(c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE));
}

public Dimension getPreferredSize()


{
return new Dimension(50,20);
}
}

28
TestBean.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.SwingUtilities;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class TestBean extends javax.swing.JFrame {
private BeanAffichage2 defileImage;
private JButton Premier;
private JTextPane text;
private BeanHeure Heure;
private JTextField Directory;
private JTextPane textdir;
private JTextField tempo;
private JRadioButton diapo;
private JRadioButton boucle;
private JButton Dernier;
private JButton Precedent;
private JButton Suivant;

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestBean inst = new TestBean();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public TestBean() {
super("Diaporama");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
this.setFocusable(false);
{
defileImage = new BeanAffichage2();
getContentPane().add(defileImage);
defileImage.setBounds(386, 159, 300, 240);

29
Thread d=new Thread(defileImage);
d.start();
}
{
Suivant = new JButton();
getContentPane().add(Suivant);
Suivant.setText("Suivant");
Suivant.setBounds(21, 159, 115, 39);
Suivant.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.suivant();
}
});
}
{
Premier = new JButton();
getContentPane().add(Premier);
Premier.setText("Premier");
Premier.setBounds(21, 217, 115, 37);
Premier.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.premier();
}
});
}
{
Precedent = new JButton();
getContentPane().add(Precedent);
Precedent.setText("Precedent");
Precedent.setBounds(168, 159, 115, 39);
Precedent.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.precedent();
}
});
}
{
Dernier = new JButton();
getContentPane().add(Dernier);
Dernier.setText("Dernier");
Dernier.setBounds(168, 217, 115, 37);
Dernier.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.dernier();
}
});
}
{
boucle = new JRadioButton();
getContentPane().add(boucle);
boucle.setText("Boucle");
boucle.setBounds(21, 271, 110, 30);
boucle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.setBoucle(boucle.isSelected());
}
});
}
{
diapo = new JRadioButton();
getContentPane().add(diapo);

30
diapo.setText("Diaporama");
diapo.setBounds(21, 308, 115, 30);
diapo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.setDiapo(diapo.isSelected());
}
});
}
{
tempo = new JTextField();
getContentPane().add(tempo);
tempo.setBounds(121, 345, 68, 31);
tempo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.setTempo(new
Integer(tempo.getText()));
}
});
}
{
text = new JTextPane();
getContentPane().add(text);
text.setText("Temporisation:");
text.setBounds(21, 347, 115, 29);
text.setOpaque(false);
text.setFont(new java.awt.Font("Segoe UI",1,12));
text.setFocusable(false);
}
{
textdir = new JTextPane();
getContentPane().add(textdir);
textdir.setText("Nom répertoire :");
textdir.setBounds(21, 17, 130, 32);
textdir.setFont(new java.awt.Font("Segoe UI",1,12));
textdir.setOpaque(false);
textdir.setFocusable(false);
}
{
Directory = new JTextField();
getContentPane().add(Directory);
Directory.setBounds(135, 17, 392, 32);
Directory.setText("C:/images/");
Directory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
defileImage.setDir(Directory.getText());
Heure.upDate();
}
});
}
{
Heure = new BeanHeure();
getContentPane().add(Heure);
Heure.setBounds(568, 21, 55, 23);
}
pack();
this.setSize(725, 462);
} catch (Exception e) {
e.printStackTrace();
}
}
}

31
2.2 Exemple d’exécusion

32
33
3 TP3 : Interaction Java-Base de données
3.1 Première partie :
On souhaite ici, dans un premier temps, développer une application pour l’interrogation de base
de données cinema.

3.1.1 JAVADOC

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

cinema.src
Class GestionBase
java.lang.Object
cinema.src.GestionBase

public class GestionBase


extends java.lang.Object
This class is used to interogate the dada base cinema.
Author:
khattab

Constructor Summary
GestionBase(java.lang.String comedien)
Contructor, make connextiopn with the data base.

Method Summary
Resultat getListMovies()
Return a comedien movies.

Methods inherited from class java.lang.Object


equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail
GestionBase
public GestionBase(java.lang.String comedien)
Contructor, make connextiopn with the data base.
Parameters:
comedien -

34
Method Detail
getListMovies
public Resultat getListMovies()
Return a comedien movies.
Returns:
Resultat
See Also:
Resultat

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

cinema.src
Class Resultat
java.lang.Object
cinema.src.Resultat

public class Resultat


extends java.lang.Object
this class is used to save data returned when the data base has been interrogated.
Author:
khattab

Constructor Summary
Resultat()
Contructor: initiate the Reusultat statut and size.

Method Summary
void addItem(java.lang.String chaine)
Adds data to a data wich had been found before.
java.util.Vector<java.lang.String> getDonnees()
Return a list of data.
java.lang.String getItem(int i)
Return the Data indexed by i.
java.lang.String getNomComedien()
Return the name of comedien.

35
int getSize()
return the number of found data.
int getStatut()
Return the request SQL statut.
void setNomComedien(java.lang.String nom)
Set the Comedien name.
void setStatut(int s)
Set the request SQL statut.

Methods inherited from class java.lang.Object


equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail
Resultat
public Resultat()
Contructor: initiate the Reusultat statut and size.
Method Detail
addItem
public void addItem(java.lang.String chaine)
Adds data to a data wich had been found before.
Parameters:
chaine -

getDonnees
public java.util.Vector<java.lang.String> getDonnees()
Return a list of data.
Returns:

getItem
public java.lang.String getItem(int i)
Return the Data indexed by i.
Parameters:
i, - index.
Returns:
data indexed by i.

getNomComedien
public java.lang.String getNomComedien()
Return the name of comedien.
Returns:
name of comedien.

getSize
public int getSize()
return the number of found data.
Returns:

36
getStatut
public int getStatut()
Return the request SQL statut.
Returns:

setNomComedien
public void setNomComedien(java.lang.String nom)
Set the Comedien name.
Parameters:
nom - comedien name.

setStatut
public void setStatut(int s)
Set the request SQL statut.
Parameters:
estate. -

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

37
3.1.2 CODE JAVA

Resultat.java
package cinema.src;

import java.util.*;

/**
* this class is used to save data returned when the data base has been
interrogated.
* @author khattab
*
*/
public class Resultat {

private Vector<String> V=new Vector<String>();


private int statut;
private String Comedien;
private int size;

/**
* Contructor: initiate the Reusultat statut and size.
*
*/

public Resultat(){
statut=0;
size=0;
}

/**
* Adds data to a data wich had been found before.
* @param chaine
*/

public void addItem(String chaine){


V.add(chaine);
size++;
}

/**
* Return a list of data.
* @return
*/

public Vector<String> getDonnees(){


return V;
}
/**
* Return the Data indexed by i.
* @param i, index.
* @return data indexed by i.
*/
public String getItem(int i){
return V.get(i);
}
/**

38
* Return the name of comedien.
* @return name of comedien.
*/
public String getNomComedien(){
return Comedien;
}
/**
* return the number of found data.
* @return
*/

public int getSize(){


return size;
}

/**
* Return the request SQL statut.
* @return
*/
public int getStatut(){
return statut;
}
/**
* Set the Comedien name.
* @param nom comedien name.
*/
public void setNomComedien(String nom){
Comedien=nom;
}
/**
* Set the request SQL statut.
* @param estate.
*/
public void setStatut(int s){
statut=s;
}
}

GestionBase.java
package cinema.src;

import java.sql.*;
import java.util.*;

class Connect{
private Connection Conn;
private final String NomBase;
public Connect(){
try{
Class.forName("org.postgresql.Driver").newInstance();
}catch(Exception e1){
System.err.println("Impossible de charger le driver "+
e1.getMessage());
System.exit(1);
}

NomBase="jdbc:postgresql://postgres.ecole.ensicaen.fr/cinema?user=khattab&

39
password=********";

try{
Conn=DriverManager.getConnection(NomBase);
}catch(SQLException e2){
System.err.println("Erreur de connexion "+ e2.getMessage());
System.exit(1);
}
}
public Connection getConn(){return Conn;}
}

/**
* This class is used to interogate the dada base cinema.
* @author khattab
*
*/

public class GestionBase {


private Connection Conn;
private Resultat result=new Resultat();
private String nomComedien;
/**
* Contructor, make connextiopn with the data base.
* @param comedien
*/
public GestionBase(String comedien){

Connect c=new Connect();


Conn=c.getConn();

try {
Statement stmt=Conn.createStatement();
result.setStatut(1);
int i=0;
ResultSet rs=stmt.executeQuery("select identc from com
where LOWER(com.identc) like LOWER('"+comedien+"%')");
while(rs.next())
{
i++;
nomComedien=rs.getString("identc");
}
if(i==1){
rs=stmt.executeQuery("select titre from
film,role,com
where LOWER(com.identc) like LOWER('"+comedien+"%') and com.numc=role.numc and
film.numf=role.numf");
while(rs.next())
result.addItem(rs.getString("titre"));
result.setNomComedien(nomComedien);

}
else if(i==0)
result.setStatut(-1);
else if(i>1)
result.setStatut(2);
rs.close();
} catch (SQLException e) {
System.err.println("Erreur de Statement "+e);
}
}

40
/**
* Return a comedien movies.
* @return Resultat
* @see Resultat
*/

public Resultat getListMovies(){

return result;
}
}

Cinema.java
package cinema.src;

import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class Cinema extends javax.swing.JFrame {

{
//Set Look & Feel
try {

javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.
WindowsLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}

private JTextPane Title;


private JTextField Com;

41
private JButton OK;
private JButton Sortir;
private JScrollPane MyScroll;
private JScrollPane jScrollPane1;
private JTextArea Resultat;
private JTextPane requeteStatut;
private JTextPane requete;
private JTextPane Titres;
private JTextPane comedien;
private JButton Erase;

/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
Cinema inst = new Cinema();
inst.setVisible(true);
}

public Cinema() {
super("Base de données cinématographique");
initGUI();
}

private void initGUI() {


try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
Title = new JTextPane();
Title.setFont(Title.getFont().deriveFont(Font.BOLD,16));
getContentPane().add(Title);
Title.setText("Base de données CINEMA");
Title.setBounds(174, 0, 340, 21);
Title.setOpaque(false);
Title.setEditable(false);
Title.setBackground(new java.awt.Color(255,255,255));
}
{
Com = new JTextField();
getContentPane().add(Com);
Com.setBounds(105, 42, 172, 28);
}
{
OK = new JButton();
getContentPane().add(OK);
OK.setText("Rechercher");
OK.setBounds(294, 42, 112, 28);
}
{
Erase = new JButton();
getContentPane().add(Erase);
Erase.setText("Effacer");
Erase.setBounds(417, 42, 115, 28);
}
{
Sortir = new JButton();
getContentPane().add(Sortir);
Sortir.setText("Quitter");
Sortir.setBounds(203, 266, 147, 28);
}

42
{
MyScroll = new JScrollPane();
getContentPane().add(MyScroll);
MyScroll.setBounds(105, 82, 427, 130);
{
Resultat = new JTextArea();
MyScroll.setViewportView(Resultat);
Resultat.setEditable(false);
}
}
{
comedien = new JTextPane();
getContentPane().add(comedien);
comedien.setText("Nom Comedien:");
comedien.setBounds(8, 42, 97, 28);
comedien.setOpaque(false);
comedien.setEditable(false);
}
{
Titres = new JTextPane();
getContentPane().add(Titres);
Titres.setText("Titres films:");
Titres.setBounds(12, 82, 87, 25);
Titres.setEditable(false);
Titres.setOpaque(false);
}
{
requete = new JTextPane();
getContentPane().add(requete);
requete.setText("Statut requête");
requete.setBounds(38, 224, 114, 29);
requete.setEditable(false);
requete.setOpaque(false);
}
{
requeteStatut = new JTextPane();
getContentPane().add(requeteStatut);
requeteStatut.setBounds(126, 224, 161, 28);
requeteStatut.setEditable(false);
requeteStatut.setOpaque(false);
}
gestionEvent gestionnaire =new gestionEvent();
Com.addActionListener(gestionnaire);
OK.addActionListener(gestionnaire);
Erase.addActionListener(gestionnaire);
Sortir.addActionListener(gestionnaire);
pack();
this.setSize(575, 335);
} catch (Exception e) {
e.printStackTrace();
}
}
private class gestionEvent implements ActionListener{
Resultat result;
GestionBase T=null;
public void actionPerformed (ActionEvent e){
if(e.getSource()==Erase){
Com.setText("");
Resultat.setText("");
}
if(e.getSource()==Sortir)

43
System.exit(1);
if(e.getSource()==OK || e.getSource()==Com){
T=new GestionBase(Com.getText());
result=T.getListMovies();
Resultat.setText("");
switch(result.getStatut())
{
case -1:
requeteStatut.setText("Pas de Comedien");
break;
case 0:
requeteStatut.setText("Pas de Connexion");
break;
case 1:
requeteStatut.setText("OK");
Com.setText(result.getNomComedien());
for(int i=0;i<result.getSize();i++)
Resultat.append(result.getItem(i)+"\n");
break;
case 2:
requeteStatut.setText("Trop de comedien");
break;
}
}
}
}

44
3.1.3 Exemple D’exécusion :

45
3.2 Deuxième partie
Dans cette partie, on veut réutiliser les classes GestionBase et Resultat qui sont dans le fichier
d’archive cinema.jar. On developpe une servelet qui interroge la base de données via cinema.jar.
Finalement la base de données sera intérroger via un navigateur.

3.2.1 CODE JAVA

Comedien.java
import java.io.IOException;
import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cinema.src.GestionBase;
import cinema.src.Resultat;

/**
* Servlet implementation class for Servlet: Comedien
*
*/
public class Comedien extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
private static final String CONTENT_TYPE = "text/html";
private Resultat result;
private GestionBase T=null;
PrintWriter out;

public Comedien() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

T=new GestionBase(request.getParameter("nomc"));
result=T.getListMovies();

switch(result.getStatut())
{
case -1:
response.setContentType(CONTENT_TYPE);
out = response.getWriter();
out.println("<p> Pas de Comedien </p>");
break;
case 0:
response.setContentType(CONTENT_TYPE);
out = response.getWriter();
out.println("<p> Pas de Connexion </p>");

46
break;
case 1:
response.setContentType(CONTENT_TYPE);
out=response.getWriter();
out.println("<p>Comedien: "+result.getNomComedien()+"</p>");
for(int i=0;i<result.getSize();i++)
out.println("<p>"+result.getItem(i)+"</p>");
break;
case 2:
response.setContentType(CONTENT_TYPE);
out = response.getWriter();
out.println("<p> Trop de comedien </p>");
break;
}

}
}

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>TP Servelet</title>
</head>
<body>
<form action="http://localhost:9080/Web/Comedien">
Nom Comedien:
<input type=text name=nomc>
<input type=submit value="ok">
</form>
</body>
</html>

47
3.2.2 Exemple d’exécusion

48
4 TP4 : Programmation JSP
4.1 Exercice 1
L’objectif est de trouver un nombre entre 1 et 100 choisi aléatoirement. Le choix aléatoire de ce
nombre sera effectué dans un javabean et l’interface d’interaction avec l’utilisateur et l’utilisateur sera
dans une page jsp.

4.1.1 JAVADOC :

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

myPackage
Class GuessBean
java.lang.Object
myPackage.GuessBean
All Implemented Interfaces:
java.io.Serializable

public class GuessBean


extends java.lang.Object
implements java.io.Serializable
See Also:
Serialized Form

Constructor Summary
GuessBean()

Method Summary
java.lang.String getHint()
This method return a String that contain information of guess.
int getNumGuess()
Return the number of guess.
boolean getSucces()
Return true if the guess is true.
void reset()
Reset GuessBean object.
void setGuess(int guess)
Set the Guess and increment the Guess's number.

49
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail
GuessBean
public GuessBean()

Method Detail
reset
public void reset()
Reset GuessBean object.

setGuess
public void setGuess(int guess)
Set the Guess and increment the Guess's number.
Parameters:
guess -

getNumGuess
public int getNumGuess()
Return the number of guess.
Returns:
the guess's number.

getHint
public java.lang.String getHint()
This method return a String that contain information of guess.
Returns:
Information if the guess is lower or higher or equal than the real number.

getSucces
public boolean getSucces()
Return true if the guess is true. False in otherwise.
Returns:
True if the guess is true. False is the guess is wrong.

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

50
4.1.2 Code JAVA
GuessBean.java
package myPackage;

import java.util.*;

public class GuessBean implements java.io.Serializable{

private int guess;


private int numGuess;
private String hint;
private boolean succes;
private int number;
Random rd=new Random();

public GuessBean(){
number=rd.nextInt(99)+1;
succes=false;
guess=-1;
numGuess=0;
hint="";
}
/**
* Reset GuessBean object.
* @return void
*/
public void reset(){
succes=false;
number=rd.nextInt(99)+1;
guess=-1;
numGuess=0;
hint="";
}
/**
* Set the Guess and increment the Guess's number.
* @param guess
*/
public void setGuess(int guess){
this.guess=guess;
numGuess++;
if(this.guess==number){
succes=true;
hint="nombre exact";
}
else
if(this.guess>number){
hint="nombre trop grand";
}
else
hint="nombre trop petit";
}
/**
* Return the number of guess.
* @return the guess's number.
*/
public int getNumGuess(){
return numGuess;

51
}
/**
* This method returns a String that contain information of guess.
* @return Information if the guess is lower or higher or equal than the
real number.
*/
public String getHint(){
return hint;
}

/**
* Return true if the guess is true. False in otherwise.
* @return True if the guess is true. False is the guess is wrong.
*/
public boolean getSucces(){
return succes;
}

numberguess.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Deviner un nombre</h1>

<jsp:useBean id="myBean" scope="session" class="myPackage.GuessBean">


</jsp:useBean>
<jsp:setProperty name="myBean" property="*"/>

<%if(myBean.getNumGuess()==0){%>
<p>Bienvenue au jeu "Deviner un nombre"<br/>
J'ai choisie un nombre entre 1 et 100<br/><br/><br/>
Choisissez un nombre:</p>
<%}else {if(myBean.getSucces()==false){%>
Non, Desole, essayer encore. Conseil: <%=myBean.getHint()%><br/>
Vous etes a <%=myBean.getNumGuess()%> essai(s)<br/>
<%} else {%>
Felicitation, Vous l'avez trouvez en <%=myBean.getNumGuess()%> essai(s)<br/>
<%
myBean.reset();}} %>
<FORM action="numberguess.jsp">
<INPUT TYPE="Text" NAME="guess" />
<INPUT TYPE="Submit" value="Soumettre"/>
</FORM>

</body>
</html>

52
4.1.3 Exemple d’exécution

Ainsi de suite jusqu’à trouver le bon nombre.

53
4.2 Exercice 2
Cet exercice consiste à développer une interface permettant aux utilisateurs de s’inscrire dans
une base de données (Ici on a crée une table « chat » dans la base de données cinema). Ensuite, les
utilisateurs peuvent se connectés en indiquant leur pseudo et leur mot de passe. Aussi ils peuvent
récupérer leur mot de passe via Javamail en indiquant leur pseudo.

4.2.1 JAVADOC

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

myPackage
Class IrcBean
java.lang.Object
myPackage.IrcBean
All Implemented Interfaces:
java.io.Serializable

public class IrcBean


extends java.lang.Object
implements java.io.Serializable
This javabean is used to get or insert some informations from de database chat.
Author:
khattab
See Also:
Serialized Form

Constructor Summary
IrcBean()

Method Summary
boolean addLogin(java.lang.String nickName, java.lang.String password,
java.lang.String firstName, java.lang.String lastName,
java.lang.String email, java.lang.String url)
This method adds new user in the database.
boolean connect(java.lang.String nickName, java.lang.String password)
Return true if the nickName and password entered are matched with the
nickName and password saved in database.
java.lang.String getInfo(java.lang.String nickName)
Return user's info.

54
java.lang.String getPassWord(java.lang.String Pseudo)
Return the user's password.
java.lang.String getProfile(java.lang.String nickName)
Return user's profile.

Methods inherited from class java.lang.Object


equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail
IrcBean
public IrcBean()

Method Detail
connect
public boolean connect(java.lang.String nickName,
java.lang.String password)
Return true if the nickName and password entered are matched with the nickName and
password saved in database. Return false if the nickNAme is not existe or the password is not
correct.
Parameters:
nickName -
password -
Returns:
true if the nickName and password entered are matched with the real nickName and password.

getInfo
public java.lang.String getInfo(java.lang.String nickName)
Return user's info. To simplify, here the info is the user's email.
Parameters:
nickName -
Returns:
user's info.

getProfile
public java.lang.String getProfile(java.lang.String nickName)
Return user's profile. Here the profile is the url picture
Parameters:
nickName -
Returns:
user's profile.

addLogin
public boolean addLogin(java.lang.String nickName,
java.lang.String password,
java.lang.String firstName,
java.lang.String lastName,
java.lang.String email,

55
java.lang.String url)
This method adds new user in the database.
Parameters:
nickName -
password -
firstName -
lastName -
email -
url -
Returns:
true if the new user is added, false if there is a problem.

getPassWord
public java.lang.String getPassWord(java.lang.String Pseudo)
Return the user's password.
Parameters:
Pseudo -
Returns:
password.

Package Class Use Tree Deprecated Index Help


PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

56
4.2.2 CODE JAVA

IrcBean.java
package myPackage;
import java.sql.*;
import java.util.*;

/**
* This javabean is used to get or insert some informations from de database chat.
* @author khattab
*
*/

public class IrcBean implements java.io.Serializable {


private Connection Conn;

public IrcBean(){
try{
Class.forName("org.postgresql.Driver").newInstance();
}catch(Exception e1){
System.err.println("Impossible de charger le driver "+
e1.getMessage());
System.exit(1);
}

String
NomBase="jdbc:postgresql://postgres.ecole.ensicaen.fr/cinema?user=khattab&
password=********";

try{
Conn=DriverManager.getConnection(NomBase);
}catch(SQLException e2){
System.err.println("Erreur de connexion "+ e2.getMessage());
System.exit(1);
}
}
/**
* Return true if the nickName and password entered are matched with the nickName
and password saved in database.
* Return false if the nickNAme is not existe or the password is not correct.
* @param nickName
* @param password
* @return true if the nickName and password entered are matched with the real
nickName and password.
* @return false if the nickNAme is not existe or the password is not correct.
*/
public boolean connect(String nickName, String password){
try {
Statement stmt=Conn.createStatement();
ResultSet rs=stmt.executeQuery("select password from chat where
nickName='"+nickName+"'");
while(rs.next()){
if(password.compareTo(rs.getString("password"))==0)
return true;
}
return false;

57
}
catch(SQLException e) {
System.err.println("Erreur de Statement "+e);
}
return false;
}

/**
* Return user's info. To simplify, here the info is the user's email.
* @param nickName
* @return user's info.
*/

public String getInfo(String nickName){


String info="";
try {
Statement stmt=Conn.createStatement();
ResultSet rs=stmt.executeQuery("select email from chat where
nickName='"+nickName+"'");
while(rs.next()){
info=rs.getString("email");
}
return info;
}
catch(SQLException e) {
System.err.println("Erreur de Statement "+e);
}
return info;
}

/**
* Return user's profile. Here the profile is the url picture
* @param nickName
* @return user's profile.
*/

public String getProfile(String nickName){


String url="";
try {
Statement stmt=Conn.createStatement();
ResultSet rs=stmt.executeQuery("select url from chat where
nickName='"+nickName+"'");
while(rs.next()){
url=rs.getString("url");
}
return url;
}
catch(SQLException e) {
System.err.println("Erreur de Statement "+e);
}
return url;
}

/**
* This method adds new user in the database.
* @param nickName
* @param password
* @param firstName
* @param lastName
* @param email

58
* @param url
* @return true if the new user is added, false if there is a problem.
*/

public boolean addLogin(String nickName, String password, String firstName,


String lastName, String email, String url){
if(url.compareTo("")==0)
url="http://www.ecole.ensicaen.fr/~khattab/img.jpg";
try{
Statement stmt=Conn.createStatement();
stmt.execute("INSERT INTO chat
VALUES('"+nickName+"','"+firstName+"','"+lastName+"','"+password+"','"+email+
"','"+url+"')");
}
catch(SQLException e){
System.out.println("Erreur de Statement "+e);
return false;
}
return true;
}
/**
* Return the user's password.
* @param Pseudo
* @return password.
*/

public String getPassWord(String Pseudo){


String password="";
try {
Statement stmt=Conn.createStatement();
ResultSet rs=stmt.executeQuery("select password from chat where
nickName='"+Pseudo+"'");
while(rs.next()){
password=rs.getString("password");
}
return password;
}
catch(SQLException e) {
System.err.println("Erreur de Statement "+e);
}
return password;
}

59
connect.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method=post action="JAVirc.jsp">
<center>
<table cellpadding=4 cellspacing=2 border=0>
<th bgcolor="#CCCCFF" colspan=2>
<font size=5>Welcome on JAVChat </font>
<br>
</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=1>
<b>NickName</b>
<br>
<input type="text" name="nickName" size=10 value="" maxlength=10>
</td>

<td valign=top>
<b>Password</b>
<br>
<input type="password" name="password" size=10 value="" maxlength=10></td>
<br>
</tr>
<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<a href=register.html>Register</a>
</td>
</tr>
<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<a href="ForgotPassword.html">Forgot your password<a>
</td>
</tr>
</table>
</center>
</form>
</body>
</html>

60
JAVirc.jsp
<!--
(c) dp 04/02

Fichier de connexion au serveur irc. Certains parametres


doivent etre completes.
-->

<jsp:useBean id="IrcBean" scope="session" class="myPackage.IrcBean">


</jsp:useBean>
<jsp:setProperty name="IrcBean" property="*"/>

<% String pseudo=request.getParameter("nickName");


String passWord=request.getParameter("password");%>

<%if(IrcBean.connect(pseudo,passWord)==false){%>
<META http-equiv="refresh" content="0;
URL=http://PC30.ecole.ensicaen.fr:9080/javirc/Reconnect.jsp">
<%}else{
String info=IrcBean.getInfo(pseudo);
String profile=IrcBean.getProfile(pseudo);
%>

<HTML>

<SCRIPT language=javascript>
function openWaitingWindow()
{
WaitingWindow = window.open
('http://www.javirc.com/JAVirc/wait.html','','width=350,height=100') ;
}

function closeWaitingWindow ()
{
WaitingWindow.close () ;
}

openWaitingWindow () ;

</SCRIPT>

<APPLET CODE="irc.class"
NAME="JAVirc"
CODEBASE="http://www.javirc.com/JAVirc"
ARCHIVE="JAVirc.jar"
WIDTH=100%
HEIGHT=80%
MAYSCRIPT>
<PARAM NAME=cabbase VALUE="JAVirc.cab">
<PARAM NAME=server VALUE="irc.javirc.com">
<PARAM NAME=port VALUE=7000>

61
<PARAM NAME=IRCName VALUE=<%=info %>>

<PARAM NAME=Nick VALUE=<%=pseudo%>>

<PARAM NAME=Password VALUE="">


<PARAM NAME=FloatingWindows VALUE="no">
<PARAM NAME="Language" VALUE="us">
<PARAM NAME="SignedApplet" VALUE="yes">
<PARAM NAME="ExpertMode" VALUE="yes">
<PARAM NAME="AllowLineCommand" VALUE="yes">
<PARAM NAME=ChangeNick VALUE="no">
<PARAM NAME=TryANotherNickWhenUsed VALUE="yes">
<PARAM NAME=useRandomNick VALUE="no">
<PARAM NAME=ListSize VALUE="50">
<PARAM NAME=EnableList VALUE="yes">
<PARAM NAME=IdentServer VALUE="yes">
<PARAM NAME=UserName VALUE="JAVchat">
<PARAM NAME=FirstCommand VALUE="MOTD;JOIN #JAVirc">
<PARAM NAME=ChangeChannel VALUE="yes">
<PARAM NAME=ChatName VALUE="JAVirc">
<PARAM NAME="CompanyHeader" VALUE="^******************************^ Welcome to
JAVirc Chat^******************************^">
<PARAM NAME="ChannelReadOnly" VALUE="no">
<PARAM NAME="QueryReadOnly" VALUE="no">
<PARAM NAME="NoticePopupWindow" VALUE="no">
<PARAM NAME=InvisibleMode VALUE="yes">
<PARAM NAME=Silence VALUE="yes">
<PARAM NAME=RestrictWhois VALUE="yes">
<PARAM NAME=QuitMessage VALUE="JAVirc http://www.javirc.com">
<PARAM NAME="URLUserGuide"
VALUE="http://www.javirc.com/JAVirc/UserGuide/JAVircUserGuide.html">
<PARAM NAME=UsePopupMenu VALUE="yes">
<PARAM NAME=Sound VALUE="yes">
<PARAM NAME=ChannelBackground VALUE="background.jpg">
<PARAM NAME=QueryBackground VALUE="background.jpg">
<PARAM NAME=ColorBackground VALUE="f0f0d0">
<PARAM NAME=ColorConnectButtonBackground VALUE="f0f0d0">
<PARAM NAME=ColorBackgroundApplet VALUE="ffffff">
<PARAM NAME=ChannelFamilyFont VALUE="SansSerif">
<PARAM NAME=ChannelStyleFont VALUE="Plain">
<PARAM NAME=ChannelSizeFont VALUE="12">
<PARAM NAME=QueryFamilyFont VALUE="SansSerif">
<PARAM NAME=QueryStyleFont VALUE="Plain">
<PARAM NAME=QuerySizeFont VALUE="12">
<PARAM NAME=ColorBackgroundDisplayChannel VALUE="f0f0ff">
<PARAM NAME=ColorBackgroundScrollbarChannel VALUE="fff0ff">
<PARAM NAME=ColorForegroundScrollbarChannel VALUE="c0c0c0">
<PARAM NAME=ColorBackgroundTextfieldChannel VALUE="f0f0ff">
<PARAM NAME=ColorForegroundTextfieldChannel VALUE="000000">
<PARAM NAME=ColorBackgroundListusersChannel VALUE="f0f0ff">
<PARAM NAME=ColorForegroundListusersChannel VALUE="000000">
<PARAM NAME=ColorBackgroundTotalusersChannel VALUE="f0f0ff">
<PARAM NAME=ColorForegroundTotalusersChannel VALUE="000000">
<PARAM NAME=ColorToolbarChannelBackground VALUE="f0f0ff">
<PARAM NAME=ColorChoiceChannelBackground VALUE="f0f0ff">
<PARAM NAME=ColorChoiceChannelForeground VALUE="000000">
<PARAM NAME=ColorButtonsChannelBackground VALUE="f0f0ff">
<PARAM NAME=ColorButtonsChannelForeground VALUE="000000">
<PARAM NAME=ColorChannelModeBackground VALUE="f0f0ff">
<PARAM NAME=ColorListBackground VALUE="f0f0ff">

62
<PARAM NAME=ColorListForeground VALUE="000000">
<PARAM NAME=ColorBackgroundDisplayQuery VALUE="c0c0ff">
<PARAM NAME=ColorBackgroundScrollbarQuery VALUE="c0c0c0">
<PARAM NAME=ColorForegroundScrollbarQuery VALUE="c0c0c0">
<PARAM NAME=ColorBackgroundTextfieldQuery VALUE="c0c0ff">
<PARAM NAME=ColorForegroundTextfieldQuery VALUE="000000">
<PARAM NAME=ColorToolbarQueryBackground VALUE="c0c0ff">
<PARAM NAME=ColorChoiceQueryBackground VALUE="c0c0ff">
<PARAM NAME=ColorChoiceQueryForeground VALUE="000000">
<PARAM NAME=ColorButtonsQueryBackground VALUE="c0c0ff">
<PARAM NAME=ColorButtonsQueryForeground VALUE="000000">
<PARAM NAME=ColorPrivateMessage VALUE="000000">
<PARAM NAME=ColorPublicMessage VALUE="000000">
<PARAM NAME=ColorSystem VALUE="000000">
<PARAM NAME=ColorInvite VALUE="006400">
<PARAM NAME=ColorQuit VALUE="ff0000">
<PARAM NAME=ColorChannelMessage VALUE="006400">
<PARAM NAME=ColorWallops VALUE="ff0000">
<PARAM NAME=ColorNickChange VALUE="006400">
<PARAM NAME=ColorTopicChange VALUE="006400">
<PARAM NAME=ColorShowTopic VALUE="006400">
<PARAM NAME=ColorCtcp VALUE="ff0000">
<PARAM NAME=ColorJoinChannel VALUE="006400">
<PARAM NAME=ColorNotice VALUE="ff0000">
<PARAM NAME=ColorAction VALUE="ff0fed">
<PARAM NAME=ColorBroadcastMessage VALUE="ff0000">
<PARAM NAME=Smiley VALUE="yes">
<PARAM NAME=Smiley0 VALUE="smile.gif|:)|yes">
<PARAM NAME=Smiley1 VALUE="smiled.gif|:d|yes">
<PARAM NAME=Smiley2 VALUE="smilep.gif|:p|yes">
<PARAM NAME=Smiley3 VALUE="wink2.gif|;)|yes">
<PARAM NAME=Smiley4 VALUE="sad.gif|:(|yes">
<PARAM NAME=Smiley5 VALUE="thumbu.gif|(y)|yes">
<PARAM NAME=Smiley6 VALUE="thumbd.gif|(n)|yes">
<PARAM NAME=Smiley7 VALUE="love.gif|(l)|yes">
<PARAM NAME=Smiley8 VALUE="unlove2.gif|(u)|yes">
<PARAM NAME=Smiley9 VALUE="camera.gif|(p)|no">
<PARAM NAME=Smiley10 VALUE="beer2.gif|(b)|no">
<PARAM NAME=Smiley11 VALUE="coctail.gif|(d)|no">
<PARAM NAME=Smiley12 VALUE="emphone.gif|(t)|no">
<PARAM NAME=Smiley13 VALUE="cat1.gif|(@)|no">
<PARAM NAME=Smiley14 VALUE="break.gif|(c)|no">
<PARAM NAME=Smiley15 VALUE="n_bulb.gif|(i)|no">
<PARAM NAME=Smiley16 VALUE="sleepz.gif|(s)|no">
<PARAM NAME=Smiley17 VALUE="hottie.gif|(h)|no">
<PARAM NAME=Smiley18 VALUE="star1.gif|(*)|no">
<PARAM NAME=Smiley19 VALUE="email.gif|(e)|no">
<PARAM NAME=Smiley20 VALUE="note.gif|(8)|no">
<PARAM NAME=Smiley21 VALUE="messenger.gif|(m)|no">
<PARAM NAME=Smiley22 VALUE="rose.gif|(f)|yes">
<PARAM NAME=Smiley23 VALUE="man.gif|(z)|no">
<PARAM NAME=Smiley24 VALUE="lips.gif|(k)|no">
<PARAM NAME=Smiley25 VALUE="gift.gif|(g)|no">
<PARAM NAME=Smiley26 VALUE="girl.gif|(x)|no">
<PARAM NAME=MircColors VALUE="yes">
<PARAM NAME=Toolbar Value="yes">
<PARAM NAME=EnableURL VALUE="yes">
<PARAM NAME=EnableNick VALUE="yes">
<PARAM NAME=Channels VALUE="#help;#aide;#france;#caen">
<PARAM NAME=Actions VALUE="applauds;hugs %;kisses % strongly">
<PARAM NAME=ChannelOperator VALUE="no">

63
<PARAM NAME=ProfilURL VALUE=<%=profile %>>
<PARAM NAME=ColorTabbedPaneBackground VALUE="f0f0ff">
<PARAM NAME=ColorTabbedPaneUsed VALUE="ff0000">
<PARAM NAME=ColorTabbedText VALUE="000000">
<PARAM NAME=ColorTabbedActiveText VALUE="0000ff">
<PARAM NAME=ColorBackgroundTopic VALUE="f0f0ff">
<PARAM NAME=ColorForegroundTopic VALUE="000000">
<PARAM NAME=ColorBackgroundCloseChannelButton VALUE="f0f0ff">
<PARAM NAME=ColorForegroundCloseChannelButton VALUE="000000">
<PARAM NAME=NickLength VALUE=9>
<PARAM NAME=StatusFamilyFont VALUE="SansSerif">
<PARAM NAME=StatusStyleFont VALUE="Plain">
<PARAM NAME=StatusSizeFont VALUE="12">
<PARAM NAME=StatusLineSpacing VALUE="16">
<PARAM NAME=ChannelLineSpacing VALUE="16">
<PARAM NAME=QueryLineSpacing VALUE="16">
<PARAM NAME=ListChannelsFamilyFont VALUE="SansSerif">
<PARAM NAME=ListChannelsStyleFont VALUE="Italic">
<PARAM NAME=ListChannelsSizeFont VALUE="20">
<PARAM NAME=ColorListStatusBackground VALUE="f0f0ff">
<PARAM NAME=ColorListStatusForeground VALUE="000000">
<PARAM NAME=ColorListCloseBackground VALUE="f0f0ff">
<PARAM NAME=ColorListCLoseForeground VALUE="000000">
<PARAM NAME=EnableChannel VALUE="yes">
<PARAM NAME="AllowQuery" VALUE="yes">
<PARAM NAME="Encode" VALUE="8859_1">

</APPLET>
</HTML>
<%}%>

Register.html
<html>
<body>
<form action="process.jsp" method=post>
<center>
<table cellpadding=4 cellspacing=2 border=0>

<th bgcolor="#CCCCFF" colspan=2>


<font size=5>JAVChat USER REGISTRATION</font>
<br>
<font size=1><sup>*</sup> Required Fields</font>
</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>NickName<sup>*</sup></b>
<br>
<input type="text" name="nickName" size=10 value="" maxlength=10>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>First Name<sup>*</sup></b>
<br>
<input type="text" name="firstName" value="" size=15 maxlength=20></td>

64
<td valign=top>
<b>Last Name<sup>*</sup></b>
<br>
<input type="text" name="lastName" value="" size=15 maxlength=20></td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>Password<sup>*</sup></b>
<br>
<input type="password" name="password1" size=10 value="" maxlength=10></td>
<td valign=top>
<b>Confirm Password<sup>*</sup></b>
<br>
<input type="password" name="password2" size=10 value="" maxlength=10></td>
<br>
</tr>

<tr bgcolor="#c8d8f8">

<td valign=top colspan=2>

<b>E-Mail<sup>*</sup></b>
<br>
<input type="text" name="email" value="" size=25 maxlength=125>
<br>

</td>

</tr>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>URL of your picture</b>
<br>
<input type="text" name="picture" size=50 maxlength=128>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>

</table>
</center>
</form>
</body>
</html>

65
Process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>

<jsp:useBean id="IrcBean" scope="session" class="myPackage.IrcBean">


</jsp:useBean>
<jsp:setProperty name="IrcBean" property="*"/>

<% String nickName=request.getParameter("nickName");


String firstName=request.getParameter("firstName");
String lastName=request.getParameter("lastName");
String passWord1=request.getParameter("password1");
String passWord2=request.getParameter("password2");
String email=request.getParameter("email");
String url=request.getParameter("picture");

if(nickName.compareTo("")*firstName.compareTo("")*lastName.compareTo("")*
passWord1.compareTo("")*passWord2.compareTo("")*email.compareTo("")==0||
passWord1.compareTo(passWord2)!=0){%>

<form action="process.jsp" method=post>


<center>
<table cellpadding=4 cellspacing=2 border=0>

<th bgcolor="#CCCCFF" colspan=2>


<font size=5>JAVChat USER REGISTRATION</font>
<br>
<font size=1><sup>*</sup> Required Fields</font>
</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>NickName<sup>*</sup></b>
<br>
<input type="text" name="nickName" size=10 value="<%=nickName %>" maxlength=10>
<%if(nickName.compareTo("")==0){%>
<br/><font color="red">Ce champ est obligatoire</font>
<%}%>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>First Name<sup>*</sup></b>
<br>
<input type="text" name="firstName" value="<%=firstName %>" size=15 maxlength=20>
<%if(firstName.compareTo("")==0){%>
<br/><font color="red">Ce champ est obligatoire</font>

66
<%}%>
</td>

<td valign=top>
<b>Last Name<sup>*</sup></b>
<br>
<input type="text" name="lastName" value="<%=lastName %>" size=15 maxlength=20>
<%if(lastName.compareTo("")==0){%>
<br/><font color="red">Ce champ est obligatoire</font>
<%}%>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>Password<sup>*</sup></b>
<br>
<br/><input type="password" name="password1" size=10 value="" maxlength=10>
<%if(passWord1.compareTo("")==0){%>
<font color="red">Ce champ est obligatoire</font>
<%}%>
</td>
<td valign=top>
<b>Confirm Password<sup>*</sup></b>
<br>
<input type="password" name="password2" size=10 value="" maxlength=10>

<%if(passWord2.compareTo(passWord1)!=0){%>
<br/><font color="red">Les mot de passe sont différents</font>
<%}%>

<%if(passWord2.compareTo("")==0){%>
<br/><font color="red">Ce champ est obligatoire</font>
<%}%>
</td>
<br>
</tr>

<tr bgcolor="#c8d8f8">

<td valign=top colspan=2>

<b>E-Mail<sup>*</sup></b>
<br>
<input type="text" name="email" size=25 value="<%=email%>" maxlength=125>
<%if(email.compareTo("")==0){%>
<br/><font color="red">Ce champ est obligatoire</font>
<%}%>
<br>

</td>

</tr>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>URL of your picture</b>
<br>
<input type="text" name="picture" value="<%=url%>" size=50 maxlength=128>

67
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>

</table>
</center>

<%}else{
if(IrcBean.addLogin(nickName, passWord1, firstName, lastName, email,
url)==false)
{%>
<META http-equiv="refresh" content="0;
URL=http://PC30.ecole.ensicaen.fr:9080/javirc/retry.jsp">
<%}else{%>

<META http-equiv="refresh" content="5;


URL=http://PC30.ecole.ensicaen.fr:9080/javirc/connect.jsp">
<%}
}%>
</body>
</html>

Reconnect.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method=post action="JAVirc.jsp">
<center>
<table cellpadding=4 cellspacing=2 border=0>

<th bgcolor="#CCCCFF" colspan=2>


<font size=5>Welcome on JAVChat </font>
<br>
<p><font color="red">Password or NickName is (are) not correct</font></p>
</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=1>
<b>NickName</b>
<br>
<input type="text" name="nickName" size=10 value="" maxlength=10>
</td>

<td valign=top>

68
<b>Password</b>
<br>
<input type="password" name="password" size=10 value="" maxlength=10></td>
<br>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<a href=register.htm>Register</a>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<a href="ForgotPassword.html">Forgot your password<a>
</td>
</tr>

</table>
</center>
</form>
</body>
</html>

retry.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<form action="process.jsp" method=post>
<center>
<table cellpadding=4 cellspacing=2 border=0>

<th bgcolor="#CCCCFF" colspan=2>


<font size=5>JAVChat USER REGISTRATION</font>
<br>
<font size=1><sup>*</sup> Required Fields</font>
</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>NickName<sup>*</sup></b>
<br>
<input type="text" name="nickName" size=10 value="" maxlength=10>
<font color="red">Erreur d'enregistrement. Veuillez Re-essayer avec un autre
pseudo</font>

69
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>First Name<sup>*</sup></b>
<br>
<input type="text" name="firstName" value="" size=15 maxlength=20></td>
<td valign=top>
<b>Last Name<sup>*</sup></b>
<br>
<input type="text" name="lastName" value="" size=15 maxlength=20></td>
</tr>

<tr bgcolor="#c8d8f8">
<td valign=top>
<b>Password<sup>*</sup></b>
<br>
<input type="password" name="password1" size=10 value="" maxlength=10></td>
<td valign=top>
<b>Confirm Password<sup>*</sup></b>
<br>
<input type="password" name="password2" size=10 value="" maxlength=10></td>
<br>
</tr>

<tr bgcolor="#c8d8f8">

<td valign=top colspan=2>

<b>E-Mail<sup>*</sup></b>
<br>
<input type="text" name="email" value="" size=25 maxlength=125>
<br>

</td>

</tr>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=2>
<b>URL of your picture</b>
<br>
<input type="text" name="picture" size=50 maxlength=128>
</td>
</tr>

<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Submit"> <input type="reset" value="Reset">
</td>
</tr>
</table>
</center>
</form>
</body>

</html>

70
ForgotPassword.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form method=post action="Mail.jsp">


<center>
<table cellpadding=4 cellspacing=2 border=0>

<th bgcolor="#CCCCFF" colspan=2>


<font size=5>Recover JAVChat password </font>
<br>

</th>

<tr bgcolor="#c8d8f8">
<td valign=top colspan=1>
<b>NickName</b>
<br>
</td>
<td valign=top colspan=1>
<input type="text" name="nickName" size=10 value="" maxlength=10>
</td>
</tr>
<tr bgcolor="#c8d8f8">
<td align=center colspan=2>
<input type="submit" value="Recover your password">
</td>
</tr>
</table>
</form>
</body>

</html>

Mail.jsp
<jsp:useBean id="IrcBean" scope="session" class="myPackage.IrcBean">
</jsp:useBean>
<jsp:setProperty name="IrcBean" property="*"/>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>

71
<body>
<%@page import="java.util.*" %>
<%@page import="javax.mail.*"%>
<%@page import="javax.mail.internet.*"%>
<%@page import="javax.activation.*" %>

<% String host="smtpc.ecole.ensicaen.fr";


String to=IrcBean.getInfo(request.getParameter("nickName"));
if(to.compareTo("")==0){%>
<h1 align="center" >The nickName you had entered is not exist</h1>
<META http-equiv="refresh" content="5;
URL=http://PC30.ecole.ensicaen.fr:9080/javirc/connect.jsp">
<% }else{
String from="khattab@ecole.ensicaen.fr";
String subject="Your passWord JAVirc";
String messageText="Bonjour,\nVoici votre password JAVicr:
"+IrcBean.getPassWord(request.getParameter("nickName"))+"\n Veuillez le garder
précieusement\n";

Properties props=System.getProperties();
props.put("mail.host",host);
props.put("mail.transport.protocol","smtp");

Session mailSession= Session.getDefaultInstance(props,null);

Message msg=new MimeMessage(mailSession);


msg.setFrom(new InternetAddress(from));
InternetAddress[] address={new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport t=mailSession.getTransport();
t.connect();
t.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
t.close();%>
<h1 align="center" >Your password has been sent, check your e-mail box</h1>
<META http-equiv="refresh" content="5;
URL=http://PC30.ecole.ensicaen.fr:9080/javirc/connect.jsp">

<%
}
%>
</body>
</html>

72
4.2.3 Exemple d’exécution

4.2.3.1 Enregistrement

Dans ce premier exemple d’exécution, l’utilisateur ne s’est pas encore enregistré.

73
74
Remarques :

• Dans le cas où l’utilisateur ne remplie pas un champ obligatoire, un message d’erreur dans ce
champ est affiché pour rappeler l’utilisateur que ce dernier est obligatoire.
• Un message d’erreur apparaît sous le champ nickName indique à l’utilisateur de choisir un
autre nickName si ce dernier est déjà enregistré dans la base de données.
• Un message d’erreur apparaît sous le champ mot de passe si l’utilisateur a entré 2 mots de
passe différents.

75
4.2.3.2 Connexion

Dans ce cas, l’utilisateur s’est déjà enregistré.

76
Remarques :

Un message d’erreur apparaîtra dans les cas suivants :

• Si le nickName n’existe pas.


• Si le mot de passe ne correspond pas au nickName.

77
4.2.3.3 Récupération de mot passe (JAVAMAIL) :
Dans ce cas, on suppose que l’utilisateur a oublié son mot de passe. La procédure est d’indiquer
son nickName et de le récupérer dans sa boite email.

78
79
Remarques :

• Un message d’erreur apparaîtra si le nickNAme n’existe pas dans la base de données.


• Si l’utilisateur ne reçoit pas l’e-mail. Alors soit l’adresse email qu’il a indiqué lors de
l’enregistrement est pas correcte. Soit le serveur SMTP est en panne.

80
5 Conclusion
Après une pratique de base de la technologie JAVA en première année. Et une autre beaucoup plus
approfondie en deuxième année d’études. Nous sommes convaincus qu’ils restent beaucoup d’astuces
encore à connaître. C’est la raison pour laquelle nous avons choisie de faire le projet d’étude de
deuxième année exclusivement en JAVA.

Nous remercions M. DUCROT pour son cours de JAVA et ses conseils lors des TP.

81

Vous aimerez peut-être aussi