◇ Structure du répertoire ◇ [Image] Contenu de la sortie et contenu de la base de données
:file_folder: book ┣━ :file_folder: src ┃ ┣━ :file_folder: sample ┃ ┃ ┣━ :page_facing_up: All.java ┃ ┃ ┣━ :page_facing_up: ProductList.java ┃ ┃ ┗━ :page_facing_up: ProductList2.java ┃ ┃ ┃ ┣━ :file_folder: dao ┃ ┃ ┣━ :page_facing_up: DAO.java ┃ ┃ ┗━ :page_facing_up: ProductDAO.java ┃ ┃ ┃ ┗━ :file_folder: bean ┃ ┗━ :page_facing_up: Product.java ┃ ┗━ :file_folder: WebContent ┣━ :file_folder: META-INF ┃ ┗━ :page_facing_up: context.xml ┃ ┗━ :file_folder: WEB-INF ┗━ :file_folder: lib ┗━ :page_facing_up: mysql-connector-java-5.1.48-bin.jar
・ Afficher l'image (à gauche) ・ Contenu de la base de données (à droite)
mysql-connector-java-8.0.18.zip
sur le site officiel (https://dev.mysql.com/downloads/connector/j/) mysql-connector-java-5.1.48-bin.jar
/ WebContent / WEB-INF / lib / mysql-connector-java-5.1.48-bin.jar
Créer dans / WebContent / META-INF / context.xml
context.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Context>
<Resource name = "jdbc/book"
auth = "Container"
type = "javax.sql.DataSource"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/book"
username = "username"
password = "password">
</Resource>
</Context>
Créer dans / src / sample / All.java
All.java
package sample;
import java.io.*;
import java.sql.*;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.*;
/**
* Servlet implementation class All
*/
@WebServlet("/All")
public class All extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
//Obtenir une connexion
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:/comp/env/jdbc/book");
Connection con = ds.getConnection();
//Transmission d'instruction SQL
PreparedStatement st = con.prepareStatement("select * from product");
//Exécution et réception des résultats
ResultSet rs = st.executeQuery();
//Affichage des données
while (rs.next()) {
out.println(
rs.getInt("id") + ":" +
rs.getString("name") + ":" +
rs.getInt("price")
);
}
//Déconnexion de la base de données
st.close();
con.close();
} catch (Exception e) {
//Erreur de connexion / instruction SQL
e.printStackTrace(out);
} // try
}
}
Créez DAO (objet d'accès aux données)! !! !! !! (^ ω ^) Créez une bibliothèque du contenu du `` 1. [Execution] servlet '' ci-dessus
DAO.java
package dao;
import java.sql.Connection;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DAO {
static DataSource ds;
public Connection getConnection() throws Exception {
//Construction du contexte initial
InitialContext ic = new InitialContext();
//Obtenir les informations de destination de la connexion à la base de données (contexte.Contenu de xml)
ds = (DataSource) ic.lookup("java:/comp/env/jdbc/book");
return ds.getConnection();
}
}
ProductList.java
package sample;
import dao.DAO;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/sample/productList")
public class ProductList extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
//Connexion DB
DAO dao = new DAO();
Connection con = dao.getConnection();
//Création SQL
PreparedStatement st = con.prepareStatement("SELECT * FROM product");
//Exécution SQL
ResultSet rs = st.executeQuery();
//Définir les données
while (rs.next()) {
out.println(
rs.getInt("id") + ":" +
rs.getString("name") + ":" +
rs.getInt("price") + "<br>"
);
}
//Déconnecter
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace(out);
}
}
}
Ci-dessus, 2) [Execution] Parce que c'est la même chose que DAO ~ Ne pas utiliser Bean ~
!! !! !! !! !! Omis! !! !! !! !!
Product.java
package bean;
public class Product implements java.io.Serializable {
private int id;
private String name;
private int price;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(int price) {
this.price = price;
}
}
ProductDAO.java
package dao;
import java.sql.*;
import java.util.*;
import bean.Product;
public class ProductDAO extends DAO {
public List<Product> listAll() throws Exception {
List<Product> list = new ArrayList<>();
//Connexion DB
Connection con = getConnection();
//Création SQL
PreparedStatement st = con.prepareStatement("SELECT * FROM product");
//Exécution SQL
ResultSet rs = st.executeQuery();
//Définir les données
while (rs.next()) {
Product p = new Product();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setPrice(rs.getInt("price"));
list.add(p);
}
//Déconnecter
st.close();
con.close();
return list;
}
}
ProductList2.java
package sample;
import java.io.*;
import java.sql.*;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.*;
import bean.Product;
import dao.ProductDAO;
@WebServlet("/sample/productList2")
public class Search2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
ProductDAO dao = new ProductDAO();
List<Product> list = dao.listAll();
for (Product p : list) {
out.println(
p.getId() + ":" +
p.getName() + ":" +
p.getPrice() + "<br>"
);
}
} catch (Exception e) {
e.printStackTrace(out);
}
}
}