ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 쇼핑몰 프로젝트 --카테고리 링크수정, 컨트롤러분리,유효성검사(화면구현)
    쇼핑몰 프로젝트 2024. 7. 2. 23:53

     

    카테고리 링크연결하는 부분이 그냥 숫자로나열되게한 하드코딩 방식으로 돼있었다. 이거를 숫자없애고 반복문을 통해서 나타나게 해주었다.

     

    cateogoryRepository

    //카테고리 부모가 null일 때 카테고리 보이게
    public List<Category> findParentCategories() {
        return em.createQuery("select c from Category c where c.categoryParent is null", Category.class)
                .getResultList();
    }
    

     

     

     

    categoryService

    //카테고리 부모가 null일 때 카테고리 보이게
    public List<Category> findParentCategories() {
        return categoryRepository.findParentCategories();
    }

     

     

    itemController

    //카테고리당 아이템 조회(정렬,검색,페이징(페이징받아서 페이징))
    @GetMapping("/ypjs/categoryItem/get/{categoryId}")
    public String getAllCategoryItem(@PathVariable("categoryId") Long categoryId,
                                     @RequestParam(value = "page",defaultValue = "0") int page,
                                     @RequestParam(value = "size",defaultValue = "3") int size,
                                     @RequestParam(value = "sortBy", defaultValue = "itemId") String sortBy,
                                     @RequestParam(value = "keyword", required = false) String keyword,
                                     Model model) {
    
        Pageable pageable = PageRequest.of(page, size);
    
        Category category = categoryService.findOneCategory(categoryId);
    
        List<ItemListDto> items = itemService.finaAllItemPagingSortBy(categoryId, keyword, pageable, sortBy);
    
    
        //총 페이지 수 계산
        int totalPages = Page.totalPages(itemService.countAllCategoryItem(keyword, categoryId), size);
    
        //카테고리
        List<Category> parentCategories = categoryService.findParentCategories();
        model.addAttribute("parentCategories", parentCategories);
    
        model.addAttribute("items",items);
        model.addAttribute("category", category);
        model.addAttribute("sortBy", sortBy); // 정렬 옵션을 다시 모델에 추가
        model.addAttribute("keyword", keyword); //검색조건 유지
        model.addAttribute("page",page); //페이징
        model.addAttribute("size",size); //페이징
        model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
    
    
    
        return "item/itemCategoryList";
    
    
    }
    
    
    
    //아이템 전체 조회
    @GetMapping("/ypjs/item/get")
    public String getAllItem(
            @RequestParam(value = "page",defaultValue = "0") int page,
            @RequestParam(value = "size",defaultValue = "3") int size,
            @RequestParam(value = "sortBy", defaultValue = "itemId") String sortBy,
            @RequestParam(value = "keyword", required = false) String keyword,
            Model model) {
    
        Pageable pageable = PageRequest.of(page, size);
    
        List<ItemListDto> items = itemService.findAllItem(keyword, pageable, sortBy);
    
        //총 페이지 수 계산
        int totalPages = Page.totalPages(itemService.countAll(keyword), size);
    
        //카테고리
        List<Category> parentCategories = categoryService.findParentCategories();
        model.addAttribute("parentCategories", parentCategories);
    
        model.addAttribute("items", items);
        model.addAttribute("sortBy", sortBy); // 정렬 옵션을 다시 모델에 추가
        model.addAttribute("keyword", keyword); //검색조건 유지
        model.addAttribute("page",page); //페이징
        model.addAttribute("size",size); //페이징
        model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
        return "item/itemList";
    
    
    }
    

     

    여기 두 부분에 

    //카테고리
    List<Category> parentCategories = categoryService.findParentCategories();
    model.addAttribute("parentCategories", parentCategories);

     

    이거 추가

     

     

    item/itemList, item/itemCategroyList에 숫자로 나열한 부분 이걸로 바꿈

    <div class="container py-5">
        <div class="row">
            <div class="col-lg-3">
                <h1 class="h2 pb-4">Categories</h1>
                <ul class="list-unstyled templatemo-accordion">
                    <!-- 최상위 부모 카테고리 목록 반복 -->
                    <li th:each="parentCategory : ${parentCategories}" class="pb-3">
                        <a class="collapsed d-flex justify-content-between h3 text-decoration-none"
                           th:href="@{/ypjs/categoryItem/get/{categoryId}(categoryId=${parentCategory.categoryId})}"
                           th:text="${parentCategory.categoryName}">
                            <i class="fa fa-fw fa-chevron-circle-down mt-1"></i>
                        </a>
                        <ul class="collapse show list-unstyled pl-3">
                            <!-- 하위 자식 카테고리 목록 반복 -->
                            <li th:each="childCategory : ${parentCategory.categoryChild}">
                                <a class="text-decoration-none"
                                   th:href="@{/ypjs/categoryItem/get/{categoryId}(categoryId=${childCategory.categoryId})}"
                                   th:text="${childCategory.categoryName}"></a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
    
    

     

     

     

    리뷰 쓴 사람 표시되게

    itemreview/itemReviewGet에  추가 

    <div class="item-info">
        <div>
            <span class="category-label">작성자&nbsp;&nbsp;:&nbsp;&nbsp;</span>
            <span th:text="${itemReview.nickname}"></span>
        </div>



     

     

    리뷰 없으면 '리뷰가 없습니다'뜨고 리뷰 있으면 링크연결

    item/itemGet에추가

    <!-- 리뷰가 있는 경우 -->
    <div th:if="${reviewCount != null and reviewCount > 0}">
        <div>
            <!-- 리뷰 링크 표시 -->
            <a th:href="@{/ypjs/itemReview/get/{itemId}(itemId=${item.itemId})}">
                Reviews  &nbsp;(<span th:text="${reviewCount}"></span>)
            </a>
        </div>
    </div>
    
    <!-- 리뷰가 없는 경우 -->
    <div th:if="${reviewCount == null or reviewCount == 0}">
        <p>리뷰가 없습니다.</p>
    </div>

     

     

     

    controller/apiController분리

    getMapping ->@Controller/ post,put,deleteMapping -> @RestController

    getMapping에 @RestController하면 json형식으로 반환됨

     

    itemController

    package ypjs.project.controller;
    
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestParam;
    import ypjs.project.domain.Category;
    import ypjs.project.domain.Item;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.itemdto.ItemListDto;
    import ypjs.project.dto.itemdto.ItemOneDto;
    import ypjs.project.dto.itemdto.ItemUpdateDto;
    import ypjs.project.service.CategoryService;
    import ypjs.project.service.ItemReviewService;
    import ypjs.project.service.ItemService;
    
    import java.util.List;
    
    @Controller
    @RequiredArgsConstructor
    public class ItemController {
    
        private final ItemService itemService;
        private final ItemReviewService itemReviewService;
        private final CategoryService categoryService;
    
    
    
        //item등록 화면
        @GetMapping("/ypjs/item/post")
        public String insert() {return "item/itemPost";}
    
    
    
        //item1개 조회
        @GetMapping("/ypjs/item/get/{itemId}")
        public String getOneItem (@PathVariable("itemId") Long itemId,
                                  Model model) {
    
            Item findItem = itemService.findOneItem(itemId);
    
            ItemOneDto item = new ItemOneDto(findItem);
    
    
            model.addAttribute("item", item);
    
            //조회수
            itemService.increaseItemCnt(itemId);
    
            //리뷰 갯수
            int reviewCount = itemReviewService.countAllItemReview(itemId);
            model.addAttribute("reviewCount", reviewCount);
    
            return "item/itemGet";
    
        }
    
    
    
        //category당 아이템 조회
    //    @GetMapping("/ypjs/categoryItem/get/{categoryId}")
    //    public CategoryOneDto getOneCategory(@PathVariable("categoryId") Long categoryId) {
    //
    //        Category category =  categoryService.findOneCategory(categoryId);
    //
    //       List<ItemListDto> items = itemService.findAllItem(categoryId);
    //
    //        return new  CategoryOneDto(category, items);
    //    }
    
    
    
    
    
        //카테고리당 아이템 조회(정렬,검색,페이징(페이징받아서 페이징))
        @GetMapping("/ypjs/categoryItem/get/{categoryId}")
        public String getAllCategoryItem(@PathVariable("categoryId") Long categoryId,
                                         @RequestParam(value = "page",defaultValue = "0") int page,
                                         @RequestParam(value = "size",defaultValue = "3") int size,
                                         @RequestParam(value = "sortBy", defaultValue = "itemId") String sortBy,
                                         @RequestParam(value = "keyword", required = false) String keyword,
                                         Model model) {
    
            Pageable pageable = PageRequest.of(page, size);
    
            Category category = categoryService.findOneCategory(categoryId);
    
            List<ItemListDto> items = itemService.finaAllItemPagingSortBy(categoryId, keyword, pageable, sortBy);
    
    
            //총 페이지 수 계산
            int totalPages = Page.totalPages(itemService.countAllCategoryItem(keyword, categoryId), size);
    
            //카테고리
            List<Category> parentCategories = categoryService.findParentCategories();
            model.addAttribute("parentCategories", parentCategories);
    
            model.addAttribute("items",items);
            model.addAttribute("category", category);
            model.addAttribute("sortBy", sortBy); // 정렬 옵션을 다시 모델에 추가
            model.addAttribute("keyword", keyword); //검색조건 유지
            model.addAttribute("page",page); //페이징
            model.addAttribute("size",size); //페이징
            model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
    
    
    
            return "item/itemCategoryList";
    
    
        }
    
    
    
        //아이템 전체 조회
        @GetMapping("/ypjs/item/get")
        public String getAllItem(
                @RequestParam(value = "page",defaultValue = "0") int page,
                @RequestParam(value = "size",defaultValue = "3") int size,
                @RequestParam(value = "sortBy", defaultValue = "itemId") String sortBy,
                @RequestParam(value = "keyword", required = false) String keyword,
                Model model) {
    
            Pageable pageable = PageRequest.of(page, size);
    
            List<ItemListDto> items = itemService.findAllItem(keyword, pageable, sortBy);
    
            //총 페이지 수 계산
            int totalPages = Page.totalPages(itemService.countAll(keyword), size);
    
            //카테고리
            List<Category> parentCategories = categoryService.findParentCategories();
            model.addAttribute("parentCategories", parentCategories);
    
            model.addAttribute("items", items);
            model.addAttribute("sortBy", sortBy); // 정렬 옵션을 다시 모델에 추가
            model.addAttribute("keyword", keyword); //검색조건 유지
            model.addAttribute("page",page); //페이징
            model.addAttribute("size",size); //페이징
            model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
            return "item/itemList";
    
    
        }
    
    
    
    
        //수정보기
        @GetMapping("/ypjs/item/update/{itemId}")
        public String udateItem(@PathVariable("itemId") Long itemId, Model model) {
    
    
    
            Item findItem = itemService.findOneItem(itemId);
    
            System.out.println(findItem);
    
            ItemUpdateDto item =  new ItemUpdateDto(
                    findItem.getItemId(),
                    findItem.getCategory().getCategoryId(),
                    findItem.getItemName(),
                    findItem.getItemContent(),
                    findItem.getItemPrice(),
                    findItem.getItemStock());
    
            model.addAttribute("item", item);
    
    
    
            return "item/itemUpdate";
        }
    
    
    
    
    
    }
    

     

     

    itemApiController

    package ypjs.project.controller;
    
    
    import jakarta.servlet.http.HttpServletResponse;
    import jakarta.servlet.http.HttpSession;
    import jakarta.validation.Valid;
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    import ypjs.project.domain.Category;
    import ypjs.project.domain.Item;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.itemdto.*;
    import ypjs.project.dto.logindto.LoginDto;
    import ypjs.project.service.CategoryService;
    import ypjs.project.service.ItemReviewService;
    import ypjs.project.service.ItemService;
    
    import java.util.List;
    
    
    @RestController
    @RequiredArgsConstructor
    public class ItemApiController {
    
        private final ItemService itemService;
    
    
    
    
        //item등록
        @PostMapping("/api/ypjs/item/post")
        public void saveItem(@RequestParam("file") MultipartFile file,
                               @Valid @ModelAttribute  ItemRequestDto requestDto,
                               @Valid @ModelAttribute  ItemFileDto itemFileDto,
                               HttpSession session, HttpServletResponse response) throws Exception {
            //멤버정보 찾기
            LoginDto.ResponseLogin responseLogin = (LoginDto.ResponseLogin) session.getAttribute("member");
    
    //        itemService.saveItem(requestDto, responseLogin.getMemberId(), itemFileDto, file);
    
            //멤버 임시로 넣어 놈
            itemService.saveItem(requestDto, 1L, itemFileDto, file);
    
            response.sendRedirect("/ypjs/item/get");
    
    
        }
    
    
    
    
    
        //수정등록
        @PostMapping("/api/ypjs/item/update/{itemId}")
        public void updateItem(@PathVariable("itemId") Long itemId,
                                        @RequestParam("file") MultipartFile file,
                                        @Valid @ModelAttribute  ItemUpdateDto itemUpdateDto,
                                        @Valid @ModelAttribute  ItemFileDto itemFileDto, Model model,
                               HttpSession session, HttpServletResponse response) throws Exception {
    
            //멤버정보 찾기
            LoginDto.ResponseLogin responseLogin = (LoginDto.ResponseLogin) session.getAttribute("member");
    
            itemService.findOneItem(itemId);
            itemService.updateItem(itemId, itemUpdateDto, itemFileDto, file);
    
    
            response.sendRedirect("/ypjs/item/get/" + itemId);
    
    
        }
    
    
        //삭제
        @DeleteMapping("/api/ypjs/item/delete/{itemId}")
        public ResponseEntity deleteItem(@PathVariable("itemId") Long itemId) {
            itemService.deleteItem(itemId);
            return ResponseEntity.ok().build();
        }
    
    
    
    
    }
    

     

    item등록, 수정은 썸네일때문에 form으로 해서 return을 redirect로 했었는데 이러면 @ResController에서는 json형식으로 반환돼서 void로 바꾸고 response.senRedirect();추가

     

     

    categoryController

    package ypjs.project.controller;
    
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import ypjs.project.domain.Category;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.categorydto.CategoryListDto;
    import ypjs.project.dto.categorydto.CategoryUpdateDto;
    import ypjs.project.dto.itemdto.ItemListDto;
    import ypjs.project.service.CategoryService;
    import ypjs.project.service.ItemService;
    
    import java.util.List;
    
    @Controller
    @RequiredArgsConstructor
    public class CategoryController {
    
    
        private final CategoryService categoryService;
        private final ItemService itemService;
    
    
        //카테고리 등록 화면
        @GetMapping("/ypjs/category/post")
        public String insert() {return "category/categoryPost";}
    
    
    
        //category 1개 조회
        @GetMapping("/ypjs/category/get/{categoryId}")
        public String getOneCategory (@PathVariable("categoryId") Long categoryId,
                                      Model model,
                                      @RequestParam(value = "page", defaultValue = "0") int page,
                                      @RequestParam(value = "size", defaultValue = "3") int size,
                                      @RequestParam(value = "keyword", required = false) String keyword) {
    
    
            Pageable pageable = PageRequest.of(page, size);
    
            Category findCategory = categoryService.findOneCategory(categoryId);
    
            List<ItemListDto> items = itemService.findAllCategoryItem(categoryId, pageable, keyword);
    
            //총 페이지 수 계산
            int totalPages = Page.totalPages(itemService.countAllCategoryItem(keyword, categoryId), size);
    
    
            model.addAttribute("category", findCategory);
            model.addAttribute("items",items);
            model.addAttribute("keyword", keyword); //검색조건 유지
            model.addAttribute("page",page); //페이징
            model.addAttribute("size",size); //페이징
            model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
            return "category/categoryGet";
    
    
        }
    
    
    
    
        //카테고리 리스트 보기
        @GetMapping("/ypjs/category/get")
        public String getCategoryList(Model model) {
    
            List<CategoryListDto> categories = categoryService.findAllCategory();
    
            model.addAttribute("categories", categories);
    
            return "category/categoryList";
        }
    
    
    
        //카테고리수정보기
        @GetMapping("/ypjs/category/update/{categoryId}")
        public String updateCategory(@PathVariable("categoryId") Long categoryId, Model model) {
    
            Category findCategory = categoryService.findOneCategory(categoryId);
    
            CategoryUpdateDto category = new CategoryUpdateDto(
                    findCategory.getCategoryId(),
                    findCategory.getCategoryParent().getCategoryId(),
                    findCategory.getCategoryName());
    
            model.addAttribute("category", category);
            return "category/categoryUpdate";
        }
    
    
    
    }
    

     

     

    categoryApiController

    package ypjs.project.controller;
    
    import jakarta.servlet.http.HttpSession;
    import jakarta.validation.Valid;
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import ypjs.project.domain.Category;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.categorydto.*;
    import ypjs.project.dto.itemdto.ItemListDto;
    import ypjs.project.dto.logindto.LoginDto;
    import ypjs.project.service.CategoryService;
    import ypjs.project.service.ItemService;
    
    import java.util.List;
    
    @RestController
    @RequiredArgsConstructor
    public class CategoryApiController {
    
        private final CategoryService categoryService;
    
    
    
    
    
        //category등록
        @PostMapping("/api/ypjs/category/post")
        public ResponseEntity saveCategory(@RequestBody @Valid CategoryRequestDto categoryRequestDtorequest,
                                           HttpSession session){
            //멤버정보 찾기
            LoginDto.ResponseLogin responseLogin = (LoginDto.ResponseLogin) session.getAttribute("member");
    
    
            Category category = categoryService.saveCategory(categoryRequestDtorequest);
    
            return ResponseEntity.ok().build();
    
        }
    
    
    
        //category수정
        @ResponseBody
        @PutMapping("/api/ypjs/category/update/{categoryId}")
        public ResponseEntity updateCategory(@PathVariable("categoryId") Long categoryId,
                                                @RequestBody @Valid CategoryUpdateDto categoryUpdateDto) {
    
            categoryService.updateCategory(categoryId, categoryUpdateDto);
            Category findCategory = categoryService.findOneCategory(categoryId);
    
            return ResponseEntity.ok().build();
    
       }
    
    
    
    
       //category삭제
        @DeleteMapping("/api/ypjs/category/delete/{categoryId}")
        public ResponseEntity deleteCategory(@PathVariable("categoryId") Long categoryId) {
            categoryService.deleteCategory(categoryId);
            return ResponseEntity.ok().build();
        }
    
    
    
    }
    

     

     

    itemReviewController

    package ypjs.project.controller;
    
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestParam;
    import ypjs.project.domain.Item;
    import ypjs.project.domain.ItemReview;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.itemdto.ItemReviewDto;
    import ypjs.project.dto.itemdto.ItemReviewListDto;
    import ypjs.project.service.ItemReviewService;
    import ypjs.project.service.ItemService;
    import ypjs.project.service.MemberService;
    
    import java.util.List;
    
    @Controller
    @RequiredArgsConstructor
    public class ItemReviewController {
    
        private final ItemReviewService itemReviewService;
        private final ItemService itemService;
        private final MemberService memberService;
    
    
        //리뷰등록 화면
        @GetMapping("/ypjs/itemReview/post/{itemId}")
        public String insert(@PathVariable("itemId") Long itemId, Model model) {
    
            Item findItem = itemService.findOneItem(itemId);
    
            model.addAttribute("item", findItem);
    
            return "itemreview/itemReviewPost";}
    
    
        //아이템 당 리뷰조회
        @GetMapping("/ypjs/itemReview/get/{itemId}")
        public String getAllItemReview(@PathVariable(name = "itemId") Long itemId, Model model,
                                       @RequestParam(value = "page",defaultValue = "0") int page,
                                       @RequestParam(value = "sortBy", defaultValue = "itemReviewId") String sortBy,
                                       @RequestParam(value = "size",defaultValue = "10") int size) {
    
    
            Pageable pageable = PageRequest.of(page, size);
    
            itemService.findOneItem(itemId);
    
            List<ItemReviewListDto> itemReviews = itemReviewService.findAllItemReview(itemId, pageable, sortBy);
    
            //총 페이지 수 계산
            int totalPages = Page.totalPages(itemReviewService.countAllItemReview(itemId), size);
    
            model.addAttribute("itemReviews", itemReviews);
            model.addAttribute("sortBy", sortBy); // 정렬 옵션을 다시 모델에 추가
            model.addAttribute("page",page); //페이징
            model.addAttribute("size",size); //페이징
            model.addAttribute("totalPages", totalPages); //총 페이지 수
    
    
            return "itemreview/itemReviewGet";
        }
    
    
    
    
    
        // 수정보기
        @GetMapping("/ypjs/itemReview/update/{itemReviewId}")
        public String updateItemReview(@PathVariable("itemReviewId") Long itemReviewId, Model model) {
            ItemReview findItemReview = itemReviewService.findOneItemReview(itemReviewId);
    
            ItemReviewDto itemReview = new ItemReviewDto(
                    findItemReview.getItem().getItemId(),
                    findItemReview.getItemReviewId(),
                    findItemReview.getItemScore(),
                    findItemReview.getItemReviewName(),
                    findItemReview.getItemReviewContent()
    
            );
    
    
    
            model.addAttribute("itemReview", itemReview);
    
            // 반환할 뷰 이름 (템플릿 파일 경로, 예: templates/itemReview/update.html)
            return "itemReview/itemReviewUpdate";
        }
    
    }
    

     

     

    itemReviewApiController

    package ypjs.project.controller;
    
    import jakarta.servlet.http.HttpSession;
    import jakarta.validation.Valid;
    import lombok.RequiredArgsConstructor;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import ypjs.project.domain.Item;
    import ypjs.project.domain.ItemReview;
    import ypjs.project.domain.Page;
    import ypjs.project.dto.itemdto.ItemReviewDto;
    import ypjs.project.dto.itemdto.ItemReviewListDto;
    import ypjs.project.dto.logindto.LoginDto;
    import ypjs.project.service.ItemReviewService;
    import ypjs.project.service.ItemService;
    import ypjs.project.service.MemberService;
    
    import java.util.List;
    
    @Controller
    @RequiredArgsConstructor
    public class ItemReviewApiController {
    
        private final ItemReviewService itemReviewService;
        private final ItemService itemService;
        private final MemberService memberService;
    
    
    
    
    
       //리뷰등록
        @ResponseBody
        @PostMapping("/api/ypjs/itemReview/post/{itemId}")
        public ResponseEntity saveItemReview(@PathVariable("itemId") Long itemId, HttpSession session, Model model,
                                            @RequestBody @Valid ItemReviewDto requestDto) {
    
            //멤버정보 찾기
            LoginDto.ResponseLogin responseLogin = (LoginDto.ResponseLogin) session.getAttribute("member");
    
            Item findItem = itemService.findOneItem(itemId);
            //ItemReview itemReview = itemReviewService.saveItemReview(requestDto, responseLogin.getMemberId());
            ItemReview itemReview = itemReviewService.saveItemReview(requestDto, 1L);
    
    
            model.addAttribute("item", findItem);
    
    
            return ResponseEntity.ok().build();
        }
    
    
        //수정등록
        @ResponseBody
        @PutMapping("/api/ypjs/itemReview/update/{itemReviewId}")
        public ResponseEntity updateItemReview(@PathVariable(name ="itemReviewId") Long itemReviewId,
                                               @RequestBody @Valid ItemReviewDto itemReviewDto,
                                               HttpSession session) {
    
            //멤버정보 찾기
            LoginDto.ResponseLogin responseLogin = (LoginDto.ResponseLogin) session.getAttribute("member");
    
    
            itemReviewService.updateItemReview(itemReviewId, itemReviewDto);
            ItemReview findItemReview = itemReviewService.findOneItemReview(itemReviewId);
    
            return ResponseEntity.ok().body(findItemReview.getItem().getItemId());
    
        }
    
    
    
    
        //삭제
        @DeleteMapping("/api/ypjs/itemReview/delete/{itemReviewId}")
        public ResponseEntity deleteItemReview(@PathVariable("itemReviewId") Long itemReviewId){
            itemReviewService.deleteItemReview(itemReviewId);
    
            return ResponseEntity.ok().build();
        }
    
    
    
    
    
    }
    

     

     

     

    dto유효성검사 추가

    Long타입은 @NotNull, String은 @NotBlank, int는 @Min으로 해줌

    itemRequestDto

    package ypjs.project.dto.itemdto;
    
    import jakarta.validation.constraints.Min;
    import jakarta.validation.constraints.NotBlank;
    import jakarta.validation.constraints.NotNull;
    import lombok.Data;
    import lombok.Getter;
    import lombok.Setter;
    import ypjs.project.domain.Member;
    
    import java.util.List;
    
    @Data
    public class ItemRequestDto {
    
        @NotNull(message = "Category ID not be null")
        private Long categoryId;
    
        @NotBlank(message = "ItemName not be null")
        private String itemName;
    
        @NotBlank(message = "ItemContent not be null")
        private String itemContent;
    
        @Min(value = 1, message = "ItemPrice must be at least 1 or greater.")
        private int itemPrice;
    
        @Min(value = 1, message = "ItemStock must be at least 1 or greater.")
        private int itemStock;
    
    
    
        public ItemRequestDto() {}
    
        public ItemRequestDto(Long categoryId, String itemName, String itemContent, int itemPrice, int itemStock) {
            this.categoryId = categoryId;
            this.itemName = itemName;
            this.itemContent = itemContent;
            this.itemPrice = itemPrice;
            this.itemStock = itemStock;
    
    
        }
    
    
    
    
    
    }
    

     

     

     

    itemUpdateDto

    package ypjs.project.dto.itemdto;
    
    import jakarta.validation.constraints.Min;
    import jakarta.validation.constraints.NotBlank;
    import jakarta.validation.constraints.NotNull;
    import lombok.Data;
    import lombok.Getter;
    
    @Data
    public class ItemUpdateDto {
        private Long itemId;
        @NotNull(message = "Category ID not be null")
        private Long categoryId;
    
        @NotBlank(message = "ItemName not be null")
        private String itemName;
        @NotBlank(message = "ItemContent not be null")
        private String itemContent;
    
        @Min(value = 1, message = "ItemPrice must be at least 1 or greater.")
        private int itemPrice;
    
        @Min(value = 1, message = "ItemStock must be at least 1 or greater.")
        private int itemStock;
    
    
    
        public ItemUpdateDto(){}
    
        public ItemUpdateDto(Long itemId,Long categoryId, String itemName, String itemContent, int itemPrice, int itemStock) {
            this.itemId = itemId;
            this.categoryId = categoryId;
            this.itemName = itemName;
            this.itemContent = itemContent;
            this.itemPrice = itemPrice;
            this.itemStock = itemStock;
    
        }
    }
    

     

     

     

    categoryRequestDto

    package ypjs.project.dto.categorydto;
    
    import jakarta.validation.constraints.NotBlank;
    import jakarta.validation.constraints.NotNull;
    import lombok.Data;
    import lombok.Getter;
    import ypjs.project.domain.Category;
    
    @Data
    public class CategoryRequestDto {
    
    
    
        @NotNull(message = "categoryParent not be null")
        private Long categoryParent;
    
        @NotBlank(message = "categoryName not be null")
        private String categoryName;
    
    
        public CategoryRequestDto() {}
        public CategoryRequestDto(Long categoryParent, String categoryName) {
    
    
            this.categoryParent = categoryParent;
            this.categoryName = categoryName;
        }
    
    
    
    }

     

     

    categoryUpdateDto

    package ypjs.project.dto.categorydto;
    
    import jakarta.validation.constraints.NotBlank;
    import jakarta.validation.constraints.NotNull;
    import lombok.Data;
    import lombok.Getter;
    import ypjs.project.domain.Category;
    
    @Data
    public class CategoryUpdateDto {
    
        @NotNull(message = "Category ID not be null")
        private Long categoryId;
    
        @NotNull(message = "categoryParent not be null")
        private Long categoryParent;
    
        @NotBlank(message = "categoryName not be null")
        private String categoryName;
    
        public CategoryUpdateDto() {}
    
        public CategoryUpdateDto(Long categoryId, Long categoryParent, String categoryName) {
            this.categoryId = categoryId;
            this.categoryParent = categoryParent;
            this.categoryName = categoryName;
        }
    }
    

     

     

    itemReviewDto

    package ypjs.project.dto.itemdto;
    
    import jakarta.validation.constraints.Min;
    import jakarta.validation.constraints.NotBlank;
    import jakarta.validation.constraints.NotNull;
    import lombok.Data;
    import lombok.Getter;
    
    import java.time.LocalDateTime;
    
    @Data
    public class ItemReviewDto {
    
        private Long itemId;
    
        private Long itemReviewId;
    
        @Min(value = 1, message = "itemScore must be at least 1 or greater.")
        private int itemScore;
    
        @NotBlank(message = "itemReviewName not be null")
        private String itemReviewName;
    
        @NotBlank(message = "itemReviewContent not be null")
        private String itemReviewContent;
    
    
        public ItemReviewDto() {}
    
    
        public ItemReviewDto(Long itemId, Long itemReviewId, int itemScore, String itemReviewName, String itemReviewContent) {
            this.itemId = itemId;
            this.itemReviewId = itemReviewId;
            this.itemScore = itemScore;
            this.itemReviewName = itemReviewName;
            this.itemReviewContent = itemReviewContent;
        }
    
    
    
    
    }
    
Designed by Tistory.