Commit 9cee75e0 by Patryk Czarnik

Obsługa zdjęć

parent c3aa8913
...@@ -32,7 +32,7 @@ public class AddToBasket extends HttpServlet { ...@@ -32,7 +32,7 @@ public class AddToBasket extends HttpServlet {
// ignorujemy błędy // ignorujemy błędy
} }
// Przekierowanie - każemy przeglądarce wejść pod ten adres. // Przekierowanie - każemy przeglądarce wejść pod ten adres.
response.sendRedirect("products8.jsp"); response.sendRedirect("products9.jsp");
} }
} }
...@@ -24,7 +24,7 @@ public class RemoveFromBasket extends HttpServlet { ...@@ -24,7 +24,7 @@ public class RemoveFromBasket extends HttpServlet {
// ignorujemy błędy // ignorujemy błędy
} }
// Przekierowanie - każemy przeglądarce wejść pod ten adres. // Przekierowanie - każemy przeglądarce wejść pod ten adres.
response.sendRedirect("products8.jsp"); response.sendRedirect("products9.jsp");
} }
} }
package sklep.photo;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import sklep.db.RecordNotFound;
@WebServlet("/photo")
public class Photo extends HttpServlet {
/* Ten serwlet wczytuje z dysku plik ze zdjęciem o podanym numerze (z parametru productId).
* Aby odesłać odpowiedź "binarną" (a nie tekstową) używamy getOutputStream() zamiast getWriter().
* Aby przeglądarka wiedziała, że otrzymuje grafikę, ustawiamy content-type image/jpeg.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String parametrId = request.getParameter("productId");
if(parametrId == null) {
return;
}
try {
int id = Integer.parseInt(parametrId);
byte[] bytes = PhotoUtil.readBytes(id);
response.setContentType("image/jpeg");
ServletOutputStream output = response.getOutputStream();
output.write(bytes);
output.close();
} catch (RecordNotFound e) {
response.setStatus(404);
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().println("Nie ma zdjęcia dla produktu o nr " + parametrId);
} catch (Exception e) {
response.setStatus(500);
e.printStackTrace();
}
}
}
package sklep.photo;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
// Włączona obsługa zapytań multipart ("z załącznikami"). Maks rozmiar zapytania/pliku: 16M
@WebServlet("/photo_upload")
@MultipartConfig(maxRequestSize = 16 * 1024 * 1024)
public class PhotoUpload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String paramId = request.getParameter("productId");
if(paramId != null) {
int productId = Integer.parseInt(paramId);
Part part = request.getPart("plik");
if(part != null) {
// przysłano plik
// Tutaj nazwa pliku jest dla nas bez znaczenia, ale gdybyśmy potrzebowali, to w ten sposób:
// String nazwaPliku = part.getSubmittedFileName();
// Przypisujemy bajty ze strumienia do pliku w katalogu ze zdjęciami:
PhotoUtil.writeStream(productId, part.getInputStream());
}
}
} catch (Exception e) {
// wypisujemy błąd, ale metoda kończy się normalnie
e.printStackTrace();
}
response.sendRedirect("products9.jsp");
}
}
package sklep.photo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import sklep.db.DBException;
import sklep.db.DBSettings;
import sklep.db.RecordNotFound;
public class PhotoUtil {
private static final String EXT = ".jpg";
public static File getFile(int productId) throws DBException, RecordNotFound {
Path path = getPath(productId);
File file = path.toFile();
if(file.exists()) {
return file;
} else {
throw new RecordNotFound("Cannot read photo for product id = " + productId);
}
}
public static byte[] readBytes(int productId) throws DBException, RecordNotFound {
Path path = getPath(productId);
try {
return Files.readAllBytes(path);
} catch (IOException e) {
// System.err.println(e);
throw new RecordNotFound("Cannot read photo for product id = " + productId);
}
}
public static void writeStream(int productId, InputStream inputStream) {
try {
Path path = getPath(productId);
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
// wypisujemy błąd, ale metoda kończy się normalnie
e.printStackTrace();
}
}
private static Path getPath(int productId) throws DBException {
String dir = DBSettings.load().getProperty("photo_dir");
String fileName = productId + EXT;
return Paths.get(dir, fileName);
}
}
...@@ -72,7 +72,7 @@ public class EditProduct extends HttpServlet { ...@@ -72,7 +72,7 @@ public class EditProduct extends HttpServlet {
// Gdy udało się zapisać, to przejdziemy z powrotem do listy. // Gdy udało się zapisać, to przejdziemy z powrotem do listy.
// To jest przekierowanie przeglądarki do inny adres. // To jest przekierowanie przeglądarki do inny adres.
response.sendRedirect("products7.jsp"); response.sendRedirect("products9.jsp");
} catch (DBException e) { } catch (DBException e) {
e.printStackTrace(); e.printStackTrace();
} }
......
<%@page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="jakarta.tags.core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lista produktów 9</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Lista produktów - wersja 9</h1>
<div class="koszyk">
<h4>Koszyk</h4>
<ul>
<%-- Zauważmy, że dla obiektu koszyk nie wykonujemy już useBean.
Po prostu zakładamy, że jest obecny (w sesji). Gdyby go nie było, to pętla się nie wykona. --%>
<c:forEach var="elm" items="${basket.elements}">
<li>${elm.productName} (${elm.quantity}) za <b>${elm.value}</b> <a href="remove_from_basket?productId=${elm.productId}">(–)</a></li>
</c:forEach>
</ul>
<p class="total">Do zapłaty: ${basket.totalValue}</p>
</div>
<form id="wyszukiwarka" method="get">
<h2>Filtr cen</h2>
<table class="formularz">
<tr><td><label for="min_price">Cena minimalna:</label></td>
<td><input id="min_price" name="min_price" type="number" value="${param.min_price}"></td></tr>
<tr><td><label for="max_price">Cena maksymalna:</label></td>
<td><input id="max_price" name="max_price" type="number" value="${param.max_price}"></td></tr>
<tr><td><button>Filtruj</button></td></tr>
</table>
</form>
<jsp:useBean id="bean" class="sklep.web.ProductBean"/>
<jsp:setProperty name="bean" property="minPrice" param="min_price"/>
<jsp:setProperty name="bean" property="maxPrice" param="max_price"/>
<c:forEach var="product" items="${bean.filteredProducts}">
<div class="product">
<img class="photo" src="photo?productId=${product.productId}" alt=""/>
<h3>${product.productName}</h3>
<div class="price">Cena: ${product.price}</div>
<div class="price">VAT ${product.vat * 100}%</div>
<c:if test="${not empty(product.description)}">
<p class="description">${product.description}</p>
</c:if>
<div class="action"><a href="add_to_basket?productId=${product.productId}">dodaj do koszyka</a></div>
<div class="action"><a href="edit?productId=${product.productId}">edytuj</a></div>
<div class="action"><a href="photo_upload.jsp?productId=${product.productId}">zmień zdjęcie</a></div>
</div>
</c:forEach>
<div class="action"><a href="edit">Dodaj nowy produkt</a></div>
</body>
</html>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment