You are on page 1of 11

Bộ môn Công nghệ phần mềm TH Công nghệ Java

BÀI THỰC HÀNH TUẦN 3


BÀI 3.2
THÊM, SỬA, XÓA DỮ LIỆU
1. Thêm dữ liệu:
Yêu cầu:
- Tạo form thêm dữ liệu vào table Product trên cơ sở dữ liệu Quanlybanhang
- Có khả năng tải hình ảnh sản phẩm lên thư mục ảnh của bộ web

Hướng dẫn:
Tạo form (file newProduct.jsp)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Product</title>
</head>
<body>
<h1>Insert Product</h1>
<form method="POST" action="newProductServlet" enctype="multipart/form-data">
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="ID"/></td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>

GV Đặng Đức Trung 1


Bộ môn Công nghệ phần mềm TH Công nghệ Java

<td>Product Type</td>
<td><input type="text" name="type"/></td>
</tr>
<tr>
<td>Product Price</td>
<td><input type="text" name="price"/></td>
</tr>
<tr>
<td>Product Image</td>
<td><input type="file" name="image" value=""></td>
</tr>
<tr>
<td colspan="2"><button>Submit</button><input type="reset"></td>
</tr>
</table>
</form>
<div>
<h5>${thongbao}</h5>

</div>
</body>
</html>

Thêm vào class DBUtils các phương thức sau:

public static int insertProduct(Product product) throws


SQLException, ClassNotFoundException
{ Connection conn = null;
int rows=0;
try{
conn =
MySQLConntUtils.getMySQLConnection();
String sql = "Insert into Product(Id,
Name,Type,Price, Image) values (?,?,?,?,?)";
PreparedStatement pstm =
conn.prepareStatement(sql);
pstm.setString(1, product.getId());
pstm.setString(2, product.getName());
pstm.setString(3, product.getType());
pstm.setInt(4, product.getPrice());
pstm.setString(5, product.getImage());
rows=pstm.executeUpdate();

GV Đặng Đức Trung 2


Bộ môn Công nghệ phần mềm TH Công nghệ Java

}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {

Logger.getLogger(AddProductServlet.class.getName())
.log(Level.SEVERE,
null, ex);
}
}
}
return rows;
}
public static void updateProduct(Product product)
throws SQLException, ClassNotFoundException
{ Connection conn = null;
try{
conn =
MySQLConntUtils.getMySQLConnection();
String sql = "Update Product set Id=?,
Name=?,Type=?,Price=?,"
+ " Image=? where Id=?";
PreparedStatement pstm =
conn.prepareStatement(sql);
pstm.setString(1, product.getId());
pstm.setString(2, product.getName());
pstm.setString(3, product.getType());
pstm.setInt(4, product.getPrice());
pstm.setString(5, product.getImage());
pstm.setString(6, product.getId());
pstm.executeUpdate();
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {

Logger.getLogger(AddProductServlet.class.getName())
.log(Level.SEVERE,

GV Đặng Đức Trung 3


Bộ môn Công nghệ phần mềm TH Công nghệ Java

null, ex);
}
}
}
}
public static void deleteProductById(Connection
conn,String id) throws SQLException {
String sql="delete from Product where id=?";
PreparedStatement pstm =
conn.prepareStatement(sql);
pstm.setString(1, id);
pstm.executeUpdate();
}
public static Product findProductById(String id) throws
SQLException, ClassNotFoundException
{ Connection conn = null;
try{
conn =
MySQLConntUtils.getMySQLConnection();
String sql = "Select * from product where
id=?";
PreparedStatement pstm =
conn.prepareStatement(sql);
pstm.setString(1, id);
ResultSet rs = pstm.executeQuery();
if (rs.next())
{ Product
pro=new
Product(rs.getString("id"),rs.getString("Name"),rs.getS
tring("Type"),

rs.getInt("Price"),rs.getString("Image"));
return pro;
}
return null;
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {

GV Đặng Đức Trung 4


Bộ môn Công nghệ phần mềm TH Công nghệ Java

Logger.getLogger(AddProductServlet.class.getName())
.log(Level.SEVERE,
null, ex);
}
}
}
}

Viết lớp newProductServlet để điều khiển thao tác thêm dữ liệu


package Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.net.URL;
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;

/**
* Servlet implementation class newProductServlet
*/
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10,
maxFileSize = 1024 * 1024 * 50,
maxRequestSize = 1024 * 1024 * 100
)
@WebServlet("/newProductServlet")
public class newProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIR = "Images";

/**
* @see HttpServlet#HttpServlet()
*/
public newProductServlet() {
super();

GV Đặng Đức Trung 5


Bộ môn Công nghệ phần mềm TH Công nghệ Java

// TODO Auto-generated constructor stub


}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
Connection conn = null; //connect SQL
try {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
conn = MySQLConntUtils.getMySQLConnection();
//xử lý tham số từ form
String id=request.getParameter("ID");
String name=request.getParameter("name");
String type=request.getParameter("type");
int price=Integer.parseInt(request.getParameter("price"));
String image="";
Part part= request.getPart("image");
String fileName=extractFileName(part);
fileName=new File(fileName).getName();

String path1=request.getContextPath();
System.out.println(path1);
part.write("D:/CNJ2022/TH1/WebContent/Images/"+fileName);
image="Images/"+fileName;

Product pro=new Product(id, name,type, price, image); //tạo đối tượng


product
//thêm đối tượng vào CSDL
DBUtils.insertProduct(conn, pro);
request.getRequestDispatcher("/NewProduct.jsp").forward(request,
response);
} catch (ClassNotFoundException ex)
{ Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch (SQLException ex)
{ Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE, null,
ex);
}finally{
if(conn != null){
try {

GV Đặng Đức Trung 6


Bộ môn Công nghệ phần mềm TH Công nghệ Java

conn.close();
} catch (SQLException ex) {
Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE,
null, ex);
}
}

doGet(request, response);
}

private String extractFileName(Part part) {


String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}

2. Sửa dữ liệu:
Yêu cầu:
- Từ bảng danh mục sản phẩm (ProductList), nhấp link edit của sản phầm nào thì mở ra
form cập nhật với thông tin sẵn có của sản phẩm đó.
- Sau khi sửa nội dung và nhấp nút Cập nhật sẽ sửa lại thông tin của sản phẩm tương ứng
trong cơ sở dữ liệu.

GV Đặng Đức Trung 7


Bộ môn Công nghệ phần mềm TH Công nghệ Java

Hướng dẫn:
Tạo form (file editProduct.jsp)
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit Product</title>
</head>
<body>
<h1>Edit Product</h1>
<form method="POST" action="editProductServlet" enctype="multipart/form-
data">
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="ID" value="${product.getID()}"/></td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="text" name="name" value="$
{product.getName()}"/></td>
</tr>
<tr>
<td>Product Type</td>
<td><input type="text" name="type" value="$
{product.getType()}"/></td>
</tr>
<tr>
<td>Product Price</td>
<td><input type="text" name="price" value="$
{product.getPrice()}"/></td>
</tr>
<tr>
<td>Product Image</td>
<td><img src="${product.getImage()}" width=100 height=100 /></td>
</tr>
<tr>
<td>Change Image</td>
<td><input type="file" name="image" value=""></td>
</tr>
<tr>
<td colspan="2"><button>Update</button><input type="reset"></td>
</tr>
</table>
</form>
<div>
<h5>${thongbao}</h5>

</div>
</body>
</html>

GV Đặng Đức Trung 8


Bộ môn Công nghệ phần mềm TH Công nghệ Java

Viết lớp editProductServlet để điều khiển thao tác hiển thị dữ liệu cũ lên form và cập nhật
dữ liệu mới lên cơ sở dữ liệu
package Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import java.net.URL;
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;

/**
* Servlet implementation class editProductServlet
*/
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 10,
maxFileSize = 1024 * 1024 * 50,
maxRequestSize = 1024 * 1024 * 100
)
@WebServlet("/editProductServlet")
public class editProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

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

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");

GV Đặng Đức Trung 9


Bộ môn Công nghệ phần mềm TH Công nghệ Java

response.getWriter().append("Served at:
").append(request.getContextPath());

String errorString = null;


String
id=request.getParameter("ID");
Product product= new Product();
try {
Connection conn = MySQLConntUtils.getMySQLConnection();

product = DBUtils.findProduct(conn,id);

} catch (SQLException e) {
e.printStackTrace();

} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

request.setAttribute("errorString",errorString);
request.setAttribute("product", product);
request.getRequestDispatcher("/EditProduct.jsp").forward(request,
response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
Connection conn = null; //connect SQL
try {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
conn = MySQLConntUtils.getMySQLConnection();
String id=request.getParameter("ID");
String name=request.getParameter("name");
String type=request.getParameter("type");
int price=Integer.parseInt(request.getParameter("price"));
String image="";
Part part= request.getPart("image");
String fileName=extractFileName(part);
fileName=new File(fileName).getName();
part.write("D:/CNJ2022/TH1/WebContent/Images/"+fileName);
image="Images/"+fileName;
Product pro=new Product(id, name,type, price, image); //tạo đối tượng
product
//thêm đối tượng vào CSDL
DBUtils.updateProduct(conn, pro);
request.getRequestDispatcher("/EditProduct.jsp").forward(request,
response);
} catch (ClassNotFoundException ex) {

GV Đặng Đức Trung 10


Bộ môn Công nghệ phần mềm TH Công nghệ Java

Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch (SQLException ex)
{ Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE, null,
ex);
}finally{
if(conn != null){
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(SignInServlet.class.getName()).log(Level.SEVERE,
null, ex);
}
}

}
//doGet(request, response);
}

private String extractFileName(Part part) {


String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}

3. Xóa dữ liệu
Yêu cầu:
- Tại bảng danh mục sản phẩm (ProductList) nhấp link Delete tại dòng sản phẩm muốn xóa
thì thông tin sản phẩm đó sẽ bị xóa khỏi cơ sở dữ liệu và cập nhật lại bảng danh mục sản
phẩm không còn sản phẩm đó.
- Sinh viên tự thực hiện yêu cầu này

GV Đặng Đức Trung 11

You might also like