projets:2018:stagejava
Ceci est une ancienne révision du document !
Table des matières
Stage Java: octobre 2018
Introduction
Découvrir la plateforme Java:
- son langage de programmation
- sa machine virtuelle
- l'environnement de développement
| Public cible | 10 jeunes |
|---|---|
| Date | 22, 23, et 24 octobre |
| Lieu | Au 214 |
Modalités
Une inscription est nécessaire pour pouvoir planifier. Une adhésion “Les Petits Hackers” (80 euros) sera demandée.
Planning et contenu
- Communication
Présent pour animer
Animation de l'atelier:
- Stéphane Blanc
- Christian Jacolot
Contacts
| Structure | Nom Prénom | Rôle sur le projet / poste |
|---|---|---|
| Maison du libre | Stéphane Blanc | Logistique et animation |
| Maison du libre | Christian JACOLOT | Logistique et animation |
Déroulé
- Présentation Java
- Installation Java JDK (OpenJDK)
- Présentation et installation de l'environnement de développement Eclipse
- Présentation du langage avec des exemples
Présentation Java
Présentation: stage_initiation_java.odp
Code de l'exemple:
package bzh.lph.stage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Devine {
private final static int max = 100;
public static void main(String[] args) throws IOException {
int nombre = (int) (Math.random() * max) + 1; // à deviner
int nbCoup = 0;
int i = 0;
do {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Entrer un entier entre 1 et 100:");
try {
i = Integer.parseInt(br.readLine());
if (i < nombre) {
System.out.println("nombre trop petit");
} else if (i > nombre) {
System.out.println("nombre trop grand");
} else {
System.out.println("bravo, vous avez deviné");
}
} catch (NumberFormatException nfe) {
System.err.println("Ce n'est pas un nombre!");
}
nbCoup += 1; // nbCoup = nbCoup +1;
} while (i != nombre);
System.out.println("Gagné en " + nbCoup + " coup(s)");
}
}
}
Java Interface Graphique
Présentation: stage_initiation_java_gui.odp
Code de l'exemple:
package bzh.lph.services;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DevineGui {
private final static int max = 100;
public static void main(String[] args) {
// jeu
int nombre = (int) (Math.random() * max) + 1; // à deviner
int nbCoup = 0;
// fenêtre
JFrame f = new JFrame("ma fenêtre");
f.setSize(640,480);
// conteneur
JPanel panel = new JPanel();
// configure le layout du conteneur
panel.setLayout(new FlowLayout());
// créer les widgets
JLabel msgLbl = new JLabel("Devine un nombre entre 1 et 100");
JLabel msgEntreLbl = new JLabel("Entrer un nombre: ");
JTextField nombreTF = new JTextField();
nombreTF.setText("99");
JButton validationBtn = new JButton("Valider mon nombre");
// quand le bouton validation est cliqué, vérifie le nombre
validationBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String textNombre = nombreTF.getText();
int i = 0;
try {
i = Integer.parseInt(textNombre);
if (i < nombre) {
JOptionPane.showConfirmDialog(f,
"nombre trop petit", "Perdu",
JOptionPane.OK_CANCEL_OPTION);
} else if (i > nombre) {
JOptionPane.showMessageDialog(f,
"nombre trop grand", "Perdu",
JOptionPane.OK_CANCEL_OPTION);
} else {
JOptionPane.showMessageDialog(f,
"vous avez deviné", "Bravo",
JOptionPane.OK_CANCEL_OPTION);
}
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(f,
"Ceci n'est pas un nombre !", "Erreur",
JOptionPane.OK_CANCEL_OPTION);
}
// nbCoup += 1; // nbCoup = nbCoup +1;
}
});
// ajoute les widgets au conteneur
panel.add(msgLbl);
panel.add(msgEntreLbl);
panel.add(nombreTF);
panel.add(validationBtn);
// ajoute le conteneur à la fenêtre
f.getContentPane().add(panel);
// la fenêtre est visible et active
f.setVisible(true);
}
}
Java Stockage: Base de données
Présentation: stage_initiation_java_stockage.odp
Code de l'exemple:
package bzh.lph.stage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GestionContact {
private static Connection conn = null;
public static void main(String[] args) {
connect();
// lireData();
// ecrireData();
// effacerData();
disconnect();
}
// connection à la base de contact
public static void connect() {
conn = null;
try {
// les paramêtres de la connexion à la base de données
String url = "jdbc:sqlite:contact.db";
// ouvrir la base de données
conn = DriverManager.getConnection(url);
System.out.println("Connexion à la base réussie.");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
// fermer la connexion à la base de données
private static void disconnect() {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
private static void lireData() {
if (conn != null) {
try {
// créer à partir de la connexion la requête
Statement stmt = conn.createStatement();
// exécuter la requête
ResultSet rs
= stmt.executeQuery("select * from contact");
// parcourir le résultat
while (rs.next()) {
int numeroContact = rs.getInt("numero");
String nomContact = rs.getString("nom");
String prenomContact = rs.getString("prenom");
System.out.println(
"Numéro: " + numeroContact
+ ", Nom: " + nomContact + ", Prénom: " + prenomContact);
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
private static void ecrireData() {
if (conn != null) {
try {
// préparer la requête
String nomContact = "Blanc";
String prenomContact = "Stéphane";
String insertionContact = "INSERT INTO contact(nom, prenom) VALUES('" + nomContact + "','"
+ prenomContact + "')";
// créer à partir de la connexion la requête
Statement stmt = conn.createStatement();
// exécuter la requête
stmt.executeUpdate(insertionContact);
System.out.println("Insertion de Stéphane: ok");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
private static void effacerData() {
if (conn != null) {
try {
// préparer la requête
int numeroJacolot = 1;
String effacterRqt = "DELETE FROM contact WHERE numero = ?";
// créer une requête à partir de la connexion
PreparedStatement deleteStmt = conn.prepareStatement(effacterRqt);
// positionner le paramètre
deleteStmt.setInt(1, numeroJacolot);
// exécuter la requête
deleteStmt.executeUpdate();
System.out.println("Christian a été effacé: ok");
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
}
mvn archetype:generate -DarchetypeGroupId=net.mdl29.test -DartifactId=resttest -DarchetypeArtifactId=maven-archetype-quickstart
pom.xml
<dependencies>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> <version>2.3.2</version>
</dependency>
</dependencies>
Class EntryPoint.java
package net.mdl29.test;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/entry-point")
public class EntryPoint {
@GET
@Path("test")
@Produces(MediaType.TEXT_PLAIN)
public String test() {
return "Test";
}
}
Class App.java
package net.mdl29.test;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public class App {
public static void main(String[] args) throws Exception {
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
Server jettyServer = new Server(8080);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
// Tells the Jersey Servlet which REST service/class to load.
jerseyServlet.setInitParameter(
"jersey.config.server.provider.classnames",
EntryPoint.class.getCanonicalName());
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
Ajouter la gestion du manifeste dans pom.xml
<build>
...
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.6</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>net.mdl29.test.App</Main-Class>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
...
</build>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.mdl29.websocket</groupId>
<artifactId>chatwebsocket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<tomcat.version>9.0.16</tomcat.version>
<websocket.version>1.1</websocket.version>
<jackson.version>2.9.8</jackson.version>
</properties>
<dependencies>
<!-- Dependency needed by the Web-socket -->
<!-- Tomcat has it, so no need to package into the war file -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>${websocket.version}</version>
<scope>provided</scope>
</dependency>
<!-- Used to serialize the message from the browser -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Sevlet jars for compilation, provided by Tomcat -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
<version>${tomcat.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
projets/2018/stagejava.1551533588.txt.gz · Dernière modification : 2024/04/16 22:26 (modification externe)
