Salut mes Amis

j'ai un projet pour importer un fichier CSV dans un fichier dans le répertoire de mon projet dont la quel j'ai la possibilité de lire et afficher ce code mais le transfert de fichier ne marche pas je ne sais pas pourquoi par contre le fichier se trouve dans un fichier temp sous le nom null voice mon servlet
Code Java : 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
package controllers;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import entities.Product;
import models.ProductModel;

/**
 * Servlet implementation class ProductServlet
 */
@WebServlet("/product")
@MultipartConfig(
		fileSizeThreshold = 10 * 1024 * 1024, maxFileSize = 5 * 1024 * 1024, maxRequestSize = 10 * 1024 * 1024)
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String UPLOAD_DIR = "assets/csv"; // le probleme est là le fichier ne se trouve pas là

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProductServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String action = request.getParameter("action");
		if (action == null) {
			doGet_Index(request, response);
		} else{
			if(action.equalsIgnoreCase("listAll")){
				doGet_listAll(request, response);
			}
		}
	}
	
	protected void doGet_listAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProductModel productModel=new ProductModel();
		List<Product> products= productModel.findAll();
		//System.out.println();
		
		request.setAttribute("products", productModel.findAll());
		products.forEach(c->System.out.println("le nom : "+c.getId()+ " / "+c.getName()+" / "+c.getDescription()+" / "+c.getPrice()));
		request.getRequestDispatcher("WEB-INF/jsps/product/listAll.jsp").forward(request, response);
	}
	

	protected void doGet_Index(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("WEB-INF/jsps/product/index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action.equalsIgnoreCase("import")) {
			doPost_Import(request, response);
		}

	}

	@SuppressWarnings("resource")
	protected void doPost_Import(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String csv = uploadFile(request, "csvFile");
			System.out.println(" le fichier CSV : " + csv);
			// Read and import csv file
			String csvPath = request.getServletContext().getRealPath("") + File.separator + UPLOAD_DIR + File.separator
					+ csv;
			ProductModel productModel = new ProductModel();
			BufferedReader bufferedReader = new BufferedReader(new FileReader(csvPath));
			String line = "";
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println("line : " + line);
				String[] result = line.trim().split(";");
				Product product = new Product();
				product.setId(result[0]);
				product.setName(result[1]);
				product.setPrice(Double.parseDouble(result[2]));
				product.setDescription(result[3]);
				productModel.create(product); 
			}
			response.sendRedirect("product?action=listAll");
		} catch (Exception e) {
			System.err.println(e.getMessage());
		}
	}

	private String getFileName(Part part) {
		final String partHeader = part.getHeader("content-disposition");
		System.out.println("******* PartHeader : " + partHeader);
		for (String content : part.getHeader("content-disposition").split(";")) {
			if (content.trim().startsWith("fileName")) {
				return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
			}
		}
		return null;
	}

	private String uploadFile(HttpServletRequest request, String name) {
		String fileName = "";
		try {
			Part filePart = request.getPart(name);
			fileName = getFileName(filePart);
			String applicationPath = request.getServletContext().getRealPath("");
			System.out.println("application Path : " + applicationPath);
			String basePath = applicationPath + File.separator + UPLOAD_DIR + File.separator;
			System.out.println("base path : " + basePath);
			InputStream inputStream = null;
			OutputStream outputStream = null;
			try {
				File outputFilePath = new File(basePath + fileName);
				inputStream = filePart.getInputStream();
				outputStream = new FileOutputStream(outputFilePath);
				int read = 0;
				final byte[] bytes = new byte[1024];
				while ((read = inputStream.read(bytes)) != -1) {
					outputStream.write(bytes, 0, read);
				}
			} catch (Exception e) {
				e.printStackTrace();
				fileName = "";
			} finally {
				if (outputStream != null) {
					outputStream.close();
				}
			}

		} catch (Exception e) {
			fileName = "";
		}
		return fileName;
	}

}
la classe est la suivante

Code Java : 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
package entities;
 
import java.io.Serializable;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name = "product")
@SuppressWarnings("serial")
public class Product implements Serializable {
 
	@Id
	@Column(name = "id", unique = true, nullable = false, length = 11)
	private String id;
	private String name;
	private Double price;
	private String description;
 
	public String getId() {
		return id;
	}
 
	public void setId(String id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public Double getPrice() {
		return price;
	}
 
	public void setPrice(Double price) {
		this.price = price;
	}
 
	public String getDescription() {
		return description;
	}
 
	public void setDescription(String description) {
		this.description = description;
	}
 
	public Product() {
		super();
	}
 
	public Product(String name, Double price, String description) {
		super();
		this.name = name;
		this.price = price;
		this.description = description;
	}
 
	public Product(String id, String name, Double price, String description) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
		this.description = description;
	}
 
}

l'hibernate Utile est la
Code Java : 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
package models;
 
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
 
public class HibernateUtil {
 
	private static final SessionFactory sessionFactory;
 
	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			Configuration configuration = new Configuration();
			configuration.configure();
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
					.buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
 
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
 
}

ProductModel

Code Java : 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
package models;
 
import java.util.List;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
 
import entities.Product;
 
public class ProductModel {
 
	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
 
	@SuppressWarnings("unchecked")
	public List<Product> findAll() {
		List<Product> products = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			products = session.createCriteria(Product.class).list();
			transaction.commit();
 
		} catch (Exception e) {
			products = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return products;
	}
 
	public void create(Product product) {
 
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.save(product);
			transaction.commit();
 
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}		
	}
 
}

le fichier hibernate.cfg.xml est le suivant
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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                                         "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<property name="hibernate.enable_lazy_load_no_trans">true</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password" />
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="entities.Product" />
	</session-factory>
</hibernate-configuration>
le fichier web.xml
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ImportCSVFile</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
index.jsp

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<jsp:forward page="product"></jsp:forward>
et dans le fichier WEB-INF/jsps/product/index.jsp il y a le code suivant

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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
 
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h3>Import Fichier CSV</h3>
	<form
		action="${pageContext.request.contextPath }/product?action=import"
		method="post" enctype="multipart/form-data">
			CSV IMPORT <input type="file" name="csvFile">
			<input type="submit" value="Import">
		</form>
</body>
</html>
qui nous envoilerons dans la page jsp situé dans la même fichier que le dernier fichier
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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>LIstes des produits</title>
</head>
<body>
	<h3>Product list</h3>
	<table border="1">
		<tr>
			<th>ID</th>
			<th>NAME</th>
			<th>PRICE</th>
			<th>DESCRIPTION</th>
		</tr>
		<c:forEach var="p" items="${products }">
			<tr>
				<td>${p.id}</td>
				<td>${p.name}</td>
				<td>${p.price}</td>
				<td>${p.description}</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>
l'affichage est bien
Dans le console j'ai mis un System.out.println ("*****") l'application path: application Path : C:\Travail Eclipse\Oxy 2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ImportCSVFile\
base path : C:\Travail Eclipse\Oxy 2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ImportCSVFile\\assets/csv\
le fichier CSV : null
l'insertion des données dans la base de données est impeccable par contre le fichier s'affiche dans le fichier temp mais pas de fichier dans le dossier assets/csv

Y a-t-il quelqu'un qui peut m'aider et bien cordialement
j'utilisais le windows 10