Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

경북대 BE_김은선_1주차 과제(3단계) #180

Open
wants to merge 19 commits into
base: eunsoni
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
# spring-gift-product
# spring-gift-product


### 1. Search Products

### 2. Add Product

### 3. Edit Product

### 4. Delete Product
18 changes: 6 additions & 12 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,31 +1,25 @@
plugins {
id 'org.springframework.boot' version '3.1.2'
id 'io.spring.dependency-management' version '1.0.15.RELEASE'
id 'java'
id 'org.springframework.boot' version '3.3.1'
id 'io.spring.dependency-management' version '1.1.5'
}

group = 'camp.nextstep.edu'
group = 'com.example'

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gift 프로젝트를 만드는건데 실제 서비스 도메인의 역순으로 패키지를 작성하는 편인 것 같은데 샘플 프로젝트의 패키지명인 것 같아요

추후 변경하려면 코드 꼬일 수 있어서 초기에 잡아두시는게 좋은 것 같습니다

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

리뷰 감사드립니다! 그런데 리뷰 내용이 잘 이해되지않는 것 같습니다.. "샘플 프로젝트의 패키지명인 것 같아요" 이건 어떤 의미일까요?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

일반적으로 패키지명은 네이버쇼핑이면 shopping.naver.com
이렇게 도메인의 역순으로 쓰는데요

진행하는 프로젝트가 카카오 선물하기니까
gift.kakao.com 정도로 해보면 어떨까 하는 의견이었어요

지금은 com.example이라서요

version = '0.0.1-SNAPSHOT'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
sourceCompatibility = '17'

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-data-jdbc'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'com.h2database:h2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

tasks.named('test') {
test {
useJUnitPlatform()
}
Binary file modified gradle/wrapper/gradle-wrapper.jar
Binary file not shown.
2 changes: 1 addition & 1 deletion gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
public class GiftApplication {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
SpringApplication.run(GiftApplication.class, args);
}

}
50 changes: 50 additions & 0 deletions src/main/java/gift/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package gift;

public class Product {
private long id;
private String name;
private int price;
private String imageUrl;

public Product() {}

public Product(long id, String name, int price, String imageUrl) {
this.id = id;
this.name = name;
this.price = price;
this.imageUrl = imageUrl;
}

// Getter and Setter methods
public long getId() {
return id;
}

public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public String getImageUrl() {
return imageUrl;
}

public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
52 changes: 52 additions & 0 deletions src/main/java/gift/ProductController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package gift;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/admin/products")
public class ProductController {

private final ProductService productService;

public ProductController(ProductService productService) {
this.productService = productService;
}

@GetMapping
public String listProducts(Model model) {
List<Product> products = productService.getAllProducts();
model.addAttribute("products", products);
return "products";
}
@GetMapping("/add")
public String showAddProductForm(Model model) {
model.addAttribute("product", new Product());
return "add-product";
}

@PostMapping("/add")
public String addProduct(@ModelAttribute Product product) {
productService.addProduct(product);
return "redirect:/admin/products";
}

@GetMapping("/edit/{id}")
public String showEditProductForm(@PathVariable Long id, Model model) {
Product product = productService.getProductById(id);
if (product == null) {
return "redirect:/admin/products";
}
model.addAttribute("product", product);
return "edit-product";
}

@GetMapping("/delete/{id}")
public String deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
return "redirect:/admin/products";
}
Comment on lines +19 to +51

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GET과 Post를 사용하는 부분에는 잘 작성해 주셨는데요
삭제와 수정 기능에는 다른 HTTP Method를 사용해주는게 명확한 표현이 되지 않을까요?

}
61 changes: 61 additions & 0 deletions src/main/java/gift/ProductService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package gift;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductService {
private final JdbcTemplate jdbcTemplate;
private final SimpleJdbcInsert simpleJdbcInsert;

public ProductService(JdbcTemplate jdbcTemplate, DataSource dataSource) {
this.jdbcTemplate = jdbcTemplate;
this.simpleJdbcInsert = new SimpleJdbcInsert(dataSource)
.withTableName("products")
.usingGeneratedKeyColumns("id");
eunsoni marked this conversation as resolved.
Show resolved Hide resolved
}

public List<Product> getAllProducts() {
String sql = "SELECT * FROM products";
return jdbcTemplate.query(sql, (rs, rowNum) -> new Product(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("price"),
rs.getString("image_url")
));
}

public Product getProductById(long id) {
String sql = "SELECT * FROM products WHERE id = ?";
return jdbcTemplate.queryForObject(sql, new Object[]{id}, (rs, rowNum) -> new Product(
rs.getLong("id"),
rs.getString("name"),
rs.getInt("price"),
rs.getString("image_url")
));
}

public void addProduct(Product product) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("name", product.getName());
parameters.put("price", product.getPrice());
parameters.put("image_url", product.getImageUrl());
Number newId = simpleJdbcInsert.executeAndReturnKey(parameters);
product.setId(newId.longValue());
}
public void updateProduct(long id, Product product) {
String sql = "UPDATE products SET name = ?, price = ?, image_url = ? WHERE id = ?";
jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getImageUrl(), id);
}

public void deleteProduct(long id) {
String sql = "DELETE FROM products WHERE id = ?";
jdbcTemplate.update(sql, id);
}
}
14 changes: 14 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
spring.application.name=spring-gift

# ?? ?? ??
server.port=8000

# H2 ?????? ??
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

# SQL ???? ??
spring.sql.init.mode=always
6 changes: 6 additions & 0 deletions src/main/resources/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE products (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price INT NOT NULL,
image_url VARCHAR(255)
eunsoni marked this conversation as resolved.
Show resolved Hide resolved
);
26 changes: 26 additions & 0 deletions src/main/resources/templates/add-product.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Add Product</title>
</head>
<body>
<h1>Add Product</h1>

<form th:action="@{/admin/products/add}" th:object="${product}" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" th:field="*{name}"><br>

<label for="price">Price:</label><br>
<input type="number" id="price" th:field="*{price}"><br>

<label for="imageUrl">Image URL:</label><br>
<input type="text" id="imageUrl" th:field="*{imageUrl}"><br>

<button type="submit">Save</button>
</form>

<a href="/admin/products">Cancel</a>

</body>
</html>
28 changes: 28 additions & 0 deletions src/main/resources/templates/edit-product.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Edit Product</title>
</head>
<body>
<h1>Edit Product</h1>

<form th:action="@{/admin/products/edit/{id}(id=${product.id})}" th:object="${product}" method="post">
<input type="hidden" th:field="*{id}">

<label for="name">Name:</label><br>
<input type="text" id="name" th:field="*{name}"><br>

<label for="price">Price:</label><br>
<input type="number" id="price" th:field="*{price}"><br>

<label for="imageUrl">Image URL:</label><br>
<input type="text" id="imageUrl" th:field="*{imageUrl}"><br>

<button type="submit">Save</button>
</form>

<a href="/admin/products">Cancel</a>

</body>
</html>
33 changes: 33 additions & 0 deletions src/main/resources/templates/products.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Product List</title>
</head>
<body>
<h1>Product List</h1>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Image</th>
<th>Actions</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.id}"></td>
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td>
<img th:src="${product.imageUrl}" style="max-width: 100px; max-height: 100px;">
</td>
<td>
<a th:href="@{/admin/products/edit/{id}(id=${product.id})}">Edit</a>
<a th:href="@{/admin/products/delete/{id}(id=${product.id})}">Delete</a>
</td>
</tr>
</table>
<br>
<a href="/admin/products/add">Add Product</a>
</body>
</html>