IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Développement Web en Java Discussion :

Ouvrir et Afficher une page Html local sur mon serveur


Sujet :

Développement Web en Java

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 20
    Points : 7
    Points
    7
    Par défaut Ouvrir et Afficher une page Html local sur mon serveur
    Bonjour a tous j'ai crée un serveur JAVA qui fonctionne correctement mais j'ai un problème. Quand je veux afficher une page html qui est dans mon disque dur le navigateur me retourne que le texte de la page et pas l'image.
    Comment faire?

  2. #2
    Membre confirmé Avatar de ruscov
    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Mars 2007
    Messages
    347
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : Belgique

    Informations professionnelles :
    Activité : Architecte de système d'information

    Informations forums :
    Inscription : Mars 2007
    Messages : 347
    Points : 500
    Points
    500
    Par défaut
    Sans code on sait pas t'aider...

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 20
    Points : 7
    Points
    7
    Par défaut
    Ma page c'est index.html

    Je fais :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     reponse.write(OuvrirPageHtml("C:/DATA/sagax/html/index.html").getBytes());
     reponse.close();

    Ma fonction OuvrirPageHtml c'est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
        private String OuvrirPageHtml(String lienPageHtml) throws IOException
        {
             BufferedReader lecteurPageHtml = new BufferedReader(new FileReader(lienPageHtml));                    //LecteurPage html permet de lire la page html qui se trouve au lien spécifié en argumenet        
     
             String line;
             String lines="";
                while ((line = lecteurPageHtml.readLine()) != null)
                {
     
                  lines=lines+line;
                }
                lecteurPageHtml.close();
                return lines;
        }
    Mon index.html est :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    <html>
    	<h1> index.html</h1>
    	<img src="Desert.jpg">
             </html>
    En faite je pense que le navigateur recherche l'image parce qu'il n'arrete pas de tourner pourtant mon image et mon index.html sont dans le même dossier

  4. #4
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Salut,

    C'est à toi de gérer le téléchargement de l'image. Le navigateur va t'envoyer une requête pour ça, commençant par l'url base de ta page et se terminant par le nom de l'image. Le code de ton serveur doit analyser le path de la requête et renvoyer en fonction, soit les pages html, soit les images.

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 20
    Points : 7
    Points
    7
    Par défaut
    Je pense que quand le navigateur recherche l'image il faut que dans l'entete de réponse le "Content-type" soit image/jpeg (pour une image .jpeg) non?

    Si oui alors comment modifier un Content-type qui était au début "text/html"?
    J'utilise la classe HTTPServer

  6. #6
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Citation Envoyé par Lowse Voir le message
    Je pense que quand le navigateur recherche l'image il faut que dans l'entete de réponse le "Content-type" soit image/jpeg (pour une image .jpeg) non?

    Si oui alors comment modifier un Content-type qui était au début "text/html"?
    J'utilise la classe HTTPServer
    Oui : le navigateur charge la page html (content type text/html) puis charge chaque image (en reconsituant leur url = base de la page + path indiqué dans src) : le serveur doit donc renvoyer les images (avec le bon content type : image/jpeg, image/png, etc...).

    Il n'y a pas à modifier le content type de quoique ce soit : chaque fichier est demandé par une requête différente dont la réponse a le content type correspondant à celui du fichier.

    Exemple vite fait :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.PrintStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
     
    import javax.activation.MimetypesFileTypeMap;
     
    public class HttpServer {
     
    	public static void main(String[] args) {
    		if ( args.length==0 ) {
    			int port = 8088;
    			Path path = Paths.get(System.getProperty("user.dir"));
    			launch(port, path);
    		}
    		else if ( args.length==1 ) {
    			int port = Integer.parseInt(args[0]);
    			Path path = Paths.get("");
    			launch(port, path);
    		}
    		else  {
    			int port = Integer.parseInt(args[0]);
    			Path path = Paths.get(args[1]);
    			if ( Files.isDirectory(path)) {
    				launch(port, path);
    			}
    			else {
    				System.err.println("Directory not found: " + path);
    			}
    		}
    	}
     
    	private static void launch(int port, Path path) {
    		HttpServer server = new HttpServer(port, path);
    		Runtime.getRuntime().addShutdownHook(new Thread(()->server.stop()));
    		try {
    			server.start();
    		} catch (IOException e) { 
    			e.printStackTrace();
    		}
    	}
     
    	private final int httpPort; 
    	private final Path path; 
    	private boolean started;
    	private ServerThread serverThread;
     
    	public HttpServer(int httpPort, Path path) {
    		this.httpPort=httpPort;
    		this.path=path;
    	}
     
    	public synchronized void start() throws IOException {
     
    		if ( !started ) {
     
    			started = true;
     
    			serverThread = new ServerThread(httpPort);
    			serverThread.start();
     
    		}
     
    	}
     
    	public synchronized void stop() {
     
    		if ( started ) {
     
    			serverThread.stopThread();
     
    			started=false;
     
    		}
     
    	}
     
    	private class ServerThread extends Thread {
     
    		private final ServerSocket server; 
    		private volatile boolean running;
    		private ExecutorService executor;
     
    		public ServerThread(int port) throws IOException {
    			super("Http server thread ("+port+")"); 
    			this.server = new ServerSocket(port);
    		}
     
    		@Override
    		public synchronized void start() {
    			running=true;
    			try {
    				super.start();
    			}
    			catch(IllegalStateException e) {
    				running=false;
    			}
    		}
     
    		@Override
    		public void run() {
     
    			executor = Executors.newSingleThreadExecutor();
     
    			while(running) {
     
    				try {
    					Socket accepted = server.accept();
    					executor.execute(()-> processAccepted(accepted));
    				} catch (IOException e) {
    					if ( running ) {
    						e.printStackTrace();
    						running=false;
    					}
    				}
     
    			}
     
    			executor.shutdown();
     
    		}
     
    		private void processAccepted(Socket accepted) {
    			try(BufferedReader reader = new BufferedReader(new InputStreamReader(accepted.getInputStream()))) {
    				// simplifié à l'extrême
    				String line = reader.readLine();
    				String filename = line.split(" ")[1];
    				if ( "/".equals(filename) ) {
    					filename = "/index.html";
    				}
    				Path fullpath = path.resolve(filename.substring(1)); 
    				if ( Files.exists(fullpath) ) {
    					String mimetype = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(filename);
    					respond(accepted, mimetype, fullpath, filename);
    				}
    				else {
    					respondError(accepted, "Not found: " + filename);
    				}
    			} catch (IOException e) { 
    				e.printStackTrace();
    			}
    		}
     
    		public void stopThread() {
    			running=false;
    			try {
    				server.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    			interrupt();
    		}
     
    	}
     
    	private void respond(Socket accepted, String mimetype, Path fullpath, String reason) throws IOException {
     
    		try(OutputStream outputStream = accepted.getOutputStream();
    			PrintStream printStream = new PrintStream(outputStream);) {
    			printStream.print("HTTP-Version 1.0 Status-Code "+200+" \r\n");
    			printHeader(printStream,"Content-type", mimeType);
    			printHeader(printStream,"Content-length", Files.size(fullpath));
    			printStream.print("\r\n");
    			try(InputStream inputStream = new BufferedInputStream(Files.newInputStream(fullpath))) {
    				byte[] buffer = new byte[2048];
    				for(int read = inputStream.read(buffer); read!=-1; read = inputStream.read(buffer)) {
    					outputStream.write(buffer, 0, read);
    				}
    			}
    		}
     
    	}
     
    	private void respondError(Socket accepted, String string) throws IOException {
     
    		StringBuilder sb = new StringBuilder();
    		sb.append("<html><body>");
    		sb.append(string);
    		sb.append("</body></html>");
     
    		respond(accepted, 500, sb, string);
     
     
    	}
     
    	private void respond(Socket accepted, int code, StringBuilder sb, String reason) throws IOException {
    		try(PrintStream printStream = new PrintStream(accepted.getOutputStream())) {
    			printStream.print("HTTP-Version 1.0 Status-Code "+code+" "+reason+"\r\n");
    			printHeader(printStream,"Content-type", "text/html");
    			printHeader(printStream,"Content-length", sb.length());
    			printStream.print("\r\n");
    			printStream.print(sb);
    		}
    	}
     
    	private void printHeader(PrintStream printStream, String name, Object value) {
    		printStream.print(name);
    		printStream.print(": " );
    		printStream.print(value);
    		printStream.print("\r\n");
    	}
     
    }
    Pour le tester, tu le lances sans paramètre et tu vas dans ton navigateur et tu tapes : http://localhost:8088/.
    Fichiers attachés Fichiers attachés

  7. #7
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 20
    Points : 7
    Points
    7
    Par défaut
    Ok merci Joel et pour un fichier css maintenant ça se passe comment?

  8. #8
    Modérateur
    Avatar de joel.drigo
    Homme Profil pro
    Ingénieur R&D - Développeur Java
    Inscrit en
    Septembre 2009
    Messages
    12 430
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur R&D - Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Septembre 2009
    Messages : 12 430
    Points : 29 131
    Points
    29 131
    Billets dans le blog
    2
    Par défaut
    Exactement pareil.

    J'ai modifié le zip pour y inclure une css (Il y avait également une erreur au niveau du content-type).

  9. #9
    Futur Membre du Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2015
    Messages
    20
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2015
    Messages : 20
    Points : 7
    Points
    7
    Par défaut
    Merci ça marche

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Afficher une page html construite dans le logiciel [TSrings]
    Par xenos dans le forum Composants VCL
    Réponses: 4
    Dernier message: 21/03/2006, 20h32
  2. afficher une page html dans un jtextpane
    Par fievel dans le forum AWT/Swing
    Réponses: 3
    Dernier message: 15/03/2006, 17h36
  3. Réponses: 5
    Dernier message: 30/11/2005, 09h48
  4. [vb.net][html] afficher une page html dans une interface vb?
    Par graphicsxp dans le forum Windows Forms
    Réponses: 1
    Dernier message: 29/09/2005, 17h31
  5. Afficher une page html
    Par Nicky dans le forum C++Builder
    Réponses: 6
    Dernier message: 14/04/2004, 14h36

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo