[Java Web] Upload file-Tích hợp CKEditor vào JSP Servlet
Đăng lúc: 03:38 PM - 20/02/2024 bởi Charles Chung - 2465Tiếp tục bài viết trước CRUD, trong bài này tôi sẽ hướng dẫn các bạn upload file (hình ảnh sản phẩm) và tích hợp CKEditor 3.x vào JSP Servlet
Giới thiệu
CKEditor (còn gọi là FCKeditor) là một trình soạn thảo mã nguồn mở theo kiểu WYSIWYG (tay làm - mắt thấy) của CKSource. Chương trình này có thể tích hợp vào các website mà không cần cài đặt. Phiên bản đầu tiên được phát hành năm 2003 và đến nay được rất nhiều người sử dụng, từ phiên bản 4.x trở đi muốn sử dụng người dùng phải bỏ chi phí mới có thể sử dụng, tuy nhiên các phiên bản từ 3.x trở về trước thì vẫn miễn phí. Trong bài này chúng ta sẽ sử dụng phiên bản 3.x.
Upload File: Trong JSP Servlet để upload file các bạn cần tải thư viện Commons FileUpload 1.5 và Commons IO 2.15 về sau đó add vào library của project, hoặc có thể khai báo thư viện maven trong file pom.xml
Ví dụ: Tích hợp CKEditor 3.x và upload file ảnh khi thêm và sửa sản phẩm
Bước 1: Mở source code của bài [Java Web] Thêm-Xóa-Sửa dữ liệu trong SQL Server sử dụng JDBC và JSP Servlet trong Eclipse
Bước 2: Tải ckeditor về và copy vào thư mục src/main/webapp
Bước 3: Mở file pom.xml bổ sung thêm dependency upload file
1 2 3 4 5 6 7 8 9 10 11 12 |
<!--https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.13.0</version> </dependency> |
Bước 4: Mở tệp tin index.jsp bổ sung dòng khai báo thư viện ckeditor.js như bên dưới
<script src="ckeditor/ckeditor.js"></script>
Bước 5: Mở tệp add.jsp sửa lại nội dung thẻ form như sau
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 |
<form action="FlowerServlet?action=insert" method="post" enctype="multipart/form-data"> <table class="table"> <tr> <td>Mã hoa</td> <td><input type="text" name="flowerid" /></td> </tr> <tr> <td>Tên hoa</td> <td><input type="text" name="flowername" /></td> </tr> <tr> <td>Đơn vị tính</td> <td><input type="text" name="unit" /></td> </tr> <tr> <td>Giá</td> <td><input type="text" name="price" value="0" /></td> </tr> <tr> <td>Giá cũ</td> <td><input type="text" name="priceold" value="0" /></td> </tr> <tr> <td>Mô tả ngắn</td> <td><textarea name="brief"></textarea></td> </tr> <tr> <td>Mô tả đầy đủ</td> <td><textarea name="description"></textarea></td> </tr> <tr> <td>Ảnh</td> <td><input type="file" name="picture" /></td> </tr> <tr> <td>Tình trạng</td> <td><input type="checkbox" name="active" checked="checked" />Còn hàng</td> </tr> <tr> <td colspan="2"><button>Lưu</button></td> </tr> </table> </form> <script> CKEDITOR.replace('description') </script> |
Bước 6: Tương tự mở tệp edit.jsp sửa lại nội dung thẻ form như sau
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 |
<form action="FlowerServlet?action=update" method="post" enctype="multipart/form-data"> <input type="hidden" name="pictureOld" value="${flower.picture}"/> <table> <tr> <td>Mã hoa</td> <td><input type="text" name="flowerid" value="${flower.flowerId}" readonly="readonly" /></td> </tr> <tr> <td>Tên hoa</td> <td><input type="text" name="flowername" value="${flower.flowerName}" /></td> </tr> <tr> <td>Đơn vị tính</td> <td><input type="text" name="unit" value="${flower.unit}" /></td> </tr> <tr> <td>Giá</td> <td><input type="text" name="price" value="${flower.price}" /></td> </tr> <tr> <td>Giá cũ</td> <td><input type="text" name="priceold" value="${flower.priceOld}" /></td> </tr> <tr> <td>Mô tả ngắn</td> <td><textarea name="brief">${flower.brief} </textarea></td> </tr> <tr> <td>Mô tả đầy đủ</td> <td><textarea name="description">${flower.description} </textarea></td> </tr> <tr> <td>Ảnh</td> <td><input type="file" name="picture"/></td> </tr> <tr> <td>Tình trạng</td> <td><c:if test="${flower.isActive()==true}"> <input type="checkbox" name="active" checked="checked" /> </c:if> <c:if test="${flower.isActive()==false}"> <input type="checkbox" name="active" /> </c:if> Còn hàng</td> </tr> <tr> <td colspan="2"><button>Lưu</button></td> </tr> </table> </form> <script> CKEDITOR.replace('description') </script> |
Bước 7: Mở tệp FlowerServlet.java chỉnh sửa lại code phần insert và update trong phương thức doGet như sau
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 |
//khai báo các hằng số cấu hình
private static final String UPLOAD_DIRECTORY = "images";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF8");
FlowerDao flowerDao = new FlowerImpl();
String action = request.getParameter("action");
if (action == null) {
request.setAttribute("flowers", flowerDao.getAll());
request.getRequestDispatcher("index.jsp?page=flowertables").forward(request, response);
} else if (action.equals("flowers")) {
request.setAttribute("flowers", flowerDao.getAll());
request.getRequestDispatcher("index.jsp?page=flowercells").forward(request, response);
} else if (action.equals("detail") || action.equals("edit")) {
String flowerid = request.getParameter("flowerid");
request.setAttribute("flower", flowerDao.getById(flowerid));
if (action.equals("detail"))
request.getRequestDispatcher("index.jsp?page=flowerdetails").forward(request, response);
else
request.getRequestDispatcher("index.jsp?page=edit").forward(request, response);
} else if (action.equals("delete")) {
String flowerid = request.getParameter("flowerid");
if (flowerDao.delete(flowerid))
request.setAttribute("msg", "Xóa thành công");
else
request.setAttribute("msg", "Xóa không thành công");
request.setAttribute("flowers", flowerDao.getAll());
request.getRequestDispatcher("index.jsp?page=flowertables").forward(request, response);
} else if (action.equals("insert") || action.equals("update")) {
// nếu request chứa file upload
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.println("Request does not contain upload data");
writer.flush();
return;
}
// cấu hình upload
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
// khởi tạo đường dẫn upload file
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
// tạo thư mục upload nếu chưa tồn tại
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
//tạo đối tượng flower
Flower f = new Flower();
//khởi tạo biến pictureold trong trường hợp sửa dữ liệu
String pictureOld=null;
try {
// phân tích request để lấy dữ liệu
List<FileItem> formItems = upload.parseRequest(request);
//lấy bộ lặp chứa các fileitem
Iterator iter = formItems.iterator();
// lặp qua từng trường trên form
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// xử lý trường tệp tin
if (!item.isFormField()) {
f.setPicture(null);
if (item.getSize()>0) {
//lấy tên file upload
String fileName = new File(item.getName()).getName();
//tạo đường dẫn file upload
String filePath = uploadPath + File.separator + fileName;
//tạo đối tượng file lưu trữ
File storeFile = new File(filePath);
// lưu tệp tin upload
item.write(storeFile);
//set tên picture
f.setPicture(fileName);
}
} else {
//lấy dữ liệu của trường trên form
String data = item.getString("UTF-8");
//set mặc định active=false
f.setActive(false);
if (item.getFieldName().equals("flowerid")) {
f.setFlowerId(data);
} else if (item.getFieldName().equals("flowername")) {
f.setFlowerName(data);
} else if (item.getFieldName().equals("unit")) {
f.setUnit(data);
} else if (item.getFieldName().equals("price")) {
f.setPrice(Float.parseFloat(data));
} else if (item.getFieldName().equals("priceold")) {
f.setPriceOld(Float.parseFloat(data));
} else if (item.getFieldName().equals("brief")) {
f.setBrief(data);
} else if (item.getFieldName().equals("description")) {
f.setDescription(data);
} else if (item.getFieldName().equals("active")) {
f.setActive(true);
}else if (item.getFieldName().equals("pictureOld")) {
pictureOld=data;
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//lấy ngày hiện tại làm ngày tạo
Date createdate = Date.valueOf(LocalDate.now());
f.setCreateDate(createdate);
//nếu picture null thì gán lại picture là pictureold (trong trường hợp sửa)
if(f.getPicture()==null)
f.setPicture(pictureOld);
if (action.equals("insert")) {
if (flowerDao.insert(f))
request.setAttribute("msg", "Thêm thành công");
else
request.setAttribute("msg", "Thêm không thành công");
} else {
if (flowerDao.update(f))
request.setAttribute("msg", "Sửa thành công");
else
request.setAttribute("msg", "Sửa không thành công");
}
//lấy toàn bộ dữ liệu
request.setAttribute("flowers", flowerDao.getAll());
//chuyển qua trang jsp hiển thị
request.getRequestDispatcher("index.jsp?page=flowertables").forward(request, response);
}
}
|
Bước 8: Run ứng dụng và kiểm tra kết quả
- Màn hình thêm sản phẩm

Link tải source code
Video
thay lời cảm ơn!
Các bài cũ hơn
- [Java Web] Thêm-Xóa-Sửa dữ liệu trong SQL Server sử dụng JDBC và JSP Servlet (04:20 PM - 19/02/2024)
- [Java Web] Truy xuất dữ liệu trong SQL Server sử dụng JDBC và JSP Servlet (01:13 PM - 02/02/2024)
- [Java Web] Tìm hiểu ngôn ngữ JSTL trong JSP Servlet (02:12 PM - 01/02/2024)
- [Java Web] Tìm hiểu về Filter trong JSP Servlet (08:02 AM - 31/01/2024)
- [Java Web] State management sử dụng Session và Cookie trong JSP Servlet (08:12 PM - 30/01/2024)












