본문 바로가기
ㆍ사이드 프로젝트

[SIDE] LUNCH - 4 / Controller-VO-repo-Service

by 매이슨 2022. 3. 14.

컨트롤러 구성

  • MainController - api통신(로그아웃제외)하는 Controller
  • SchedulerController - cron* 10시 20분 마다 자동으로 식당 선정해주는 Controller
  • ViewController - view(jsp페이지) 통신하는 Controller

  public String today() {
    return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
  }

// 전역 변수 today
// 최초 모습
	String today() = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
// 위와 같은 모습이었지만 
// 최상단 today 메소드로 변경되었다.

// 이유는 최초 서버가동일의 날짜가 고정이 되었긴때문인데
// 그 시점이 서버가동 시점인지, 최초 호출 시점인지는 불명확하다.

  • MainController 리스트 ("/api/*")
// ("/login")

  // 로그인 index -> lunch로 감
  @PostMapping("/login")
  @ResponseBody
  public LunchVO loginPOST(HttpSession session, @RequestBody MemberVO memberVO) throws Exception{
    logger.info(" Controller -> loginPOST -> memberVO : "+memberVO);
    if(lunchMapperInterface.doLogin(memberVO)){ // 로그인 확인 true
      logger.info(" loginPOST -> 로그인 성공");
      session.setAttribute("id",memberVO.getId());
      //session.setMaxInactiveInterval(60*60*5); //5시간
      session.setMaxInactiveInterval(-1); // 무한대
      return new ResultVO("success");
    }
    return new ResultVO("asdf");
  }
// ("/logout")

  // 로그아웃
  @RequestMapping("/logout")
  public String logoutPOST(HttpSession session){
    session.invalidate();
    return "redirect:/";
  }
  // ("/insertNewStore")
  
  // lunch -> 새로운식당추가
  @PostMapping("/insertNewStore")
  @ResponseBody
  public ResultVO insertNewStorePOST(@RequestBody NewStoreVO newStoreVO) {
    lunchMapperInterface.insertNewStore(newStoreVO);
    return new ResultVO("success");
  }
// ("/choice")

  // lunch -> 식당 선택
  @PostMapping("/choice")
  @ResponseBody
  public ResultVO choicePOST(HttpSession session, @RequestBody StorePickedVO storePickedVO) throws Exception {
    logger.info(" Controller -> choicePOST -> storePickedVO : "+storePickedVO);
    lunchService.choiceStore((String) session.getAttribute("id"),storePickedVO);
    return new ResultVO("success");
    //return new ResultVO("asdf");
  }
// ("/noLunchToday")

// lunch -> 결식 : choicemenu & dailystore 둘다 입력
  @PostMapping("/noLunchToday")
  @ResponseBody
  public ResultVO noLunchTodayPOST(HttpSession session) throws Exception{
    logger.info(" Controller -> noLunchTodayPOST -> 밥안먹는사람~~~ : " + session.getAttribute("id"));
    String id = (String) session.getAttribute("id");
  
    // 있으머는 어~~~업데이트
    if(lunchMapperInterface.checkStore(id, today())){
      logger.info("업데이트");
      lunchMapperInterface.updateNoLunchTodayStore(id, today());
      lunchMapperInterface.updateNoLunchTodayMenu(id, today());
    }else{
      // 없으면 인사트
      int seq = lunchMapperInterface.getDateSeq(today()) + 1;
      logger.info("인써트");
      lunchMapperInterface.noLunchTodayStore(id,today(),seq);
      lunchMapperInterface.noLunchTodayMenu(id,today(),seq);
    }
    return new ResultVO("success");
  }
// ("/insertMainMenu")

  // menu - 새로운 메인메뉴 추가
  @PostMapping("/insertMainMenu")
  @ResponseBody
  public ResultVO insertMainMenuPOST(@RequestBody MainMenuVO mainMenuVO){
    logger.info("mainMenuVO -> " + mainMenuVO);
    lunchMapperInterface.insertMainMenu(mainMenuVO);
    return new ResultVO(String.valueOf(lunchMapperInterface.getLatestMenuSeq()));
  }
// ("/insertChoiceMenu")

  // menu -> 메인메뉴 선택
  @PostMapping("/insertChoiceMenu")
  @ResponseBody
  public ResultVO insertChoiceMenuPOST(@RequestBody ChoiceMenuVO choiceMenuVO){
    logger.info("choiceMenuVO -> " + choiceMenuVO);
    choiceMenuVO.setDate_seq(lunchMapperInterface.getDateSeqFromChoiceStore(today()) + 1);
    choiceMenuVO.setDate(today());
    lunchMapperInterface.insertChoiceMenu(choiceMenuVO);
    return new ResultVO("success");
  }
// ("/deleteOrder")

  // menu -> 주문 삭제
  @PostMapping("/deleteOrder")
  @ResponseBody
  public ResultVO deleteOrderPOST(@RequestBody int choicemenuseq){
    lunchMapperInterface.deleteOrder(choicemenuseq);
    return new ResultVO("success");
  }

https://github.com/MasonBaek/springboot_PickingLunchMenu/blob/main/mrsbok/src/main/java/com/lunch/mrsbok/controller/MainController.java

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com


  • SchedulerController 리스트
// randomStore()

	// 월~금 10시20분에 실행
	// 선택된 식당 있으면 선택된 식당중 랜덤 선택
	// 선택된 식당 없으면 기존 DB에 있는 식당중 랜덤 선택
	@Scheduled(cron = "0 20 10 * * MON-FRI")
	public void randomStore() throws Exception {
		logger.info("cron 시작");
		String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd"));
		List<StoreRandomVO> OfficeAList = lunchMapperInterface.getStoreListOfficeAForRandom(today);
		List<StoreRandomVO> officeBList = lunchMapperInterface.getStoreListOfficeBForRandom(today);
		Random random = new Random();
		// 돌림판 돌리기
		if(!officeBList.isEmpty()){ // 사용자가 정한메뉴가 있을때
			// B 사무실 랜덤 식당 디비에 넣기
			lunchMapperInterface.insertDailyStoreOfficeB(officeBList.get(random.nextInt(officeBList.size())).getStorePicked(), today);
			logger.info("cron 식당선택있음 사무실B");
		} else { // 사용자가 정한 메뉴가 없을때
			// 전체 식당 메뉴 들고 오고
			List<StoreVO> list = lunchMapperInterface.getStore();
			// B 사무실 랜덤 식당 디비에 넣기
			lunchMapperInterface.insertDailyStoreOfficeB(list.get(random.nextInt(list.size())).getStore(),today);
			logger.info("cron 식당선택없음 사무실B");
		}
		
		if(!OfficeAList.isEmpty()){ // 사용자가 정한메뉴가 있을때
			// A 사무실 랜덤 식당 디비에 넣기
			lunchMapperInterface.insertDailyStoreOfficeA(OfficeAList.get(random.nextInt(OfficeAList.size())).getStorePicked(),today);
			logger.info("cron 식당선택있음 사무실A");
		} else { // 사용자가 정한 메뉴가 없을때
			// 전체 식당 메뉴 들고 오고
			List<StoreVO> list = lunchMapperInterface.getStore();
			// A 사무실 랜덤 식당 디비에 넣기
			lunchMapperInterface.insertDailyStoreOfficeA(list.get(random.nextInt(list.size())).getStore(),today);
			logger.info("cron 식당선택없음 사무실A");
		}
		logger.info("cron 식당 DB에 넣음 사무실A");
	}

https://github.com/MasonBaek/springboot_PickingLunchMenu/blob/main/mrsbok/src/main/java/com/lunch/mrsbok/controller/SchedulerController.java

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com


  • ViewController 리스트 ("/*")
 // ("/")

  @RequestMapping("/")
  public String index() throws Exception{
    String first = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-08-29-00"));
    String last = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-13-01-00"));
    SimpleDateFormat SDF = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
    Date firstParse = SDF.parse(first);
    Date lastParse = SDF.parse(last);
    logger.info("\n\t\t 홈 ");
    
    if(new Date().after(firstParse) && new Date().before(lastParse) ){
      return "index";
    }
    return "ready";
  }

"/lunch" 페이지에서 사용되는 메소드 한번에 리스트

/* lunch */
  @RequestMapping("/lunch")
  public String lunch(HttpSession session, Model model) throws  Exception {
    if(session.getAttribute("id")==null){
      return "redirect:/";
    }
    String first = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-08-29-00"));
    String second = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-10-19-00"));
    String last = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-13-01-00"));
    SimpleDateFormat SDF = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
    Date firstParse = SDF.parse(first);
    Date secondParse = SDF.parse(second);
    Date lastParse = SDF.parse(last);
    logger.info("secondParse -> " + secondParse);
    if(new Date().after(secondParse) && new Date().before(lastParse) ){
      logger.info("10시 20분 부터 /menu페이지로 이동");
      return "redirect:/menu";
    }else if(new Date().before(firstParse) || new Date().after(lastParse) ){
      return "redirect:/ready";
    }
    
    // 식당리스트 가져오기
    List<StoreVO> list = lunchService.getStoreList();
    logger.info("list -> "+ list);
    model.addAttribute("storeList",list);
    // 내가 선택한 식당 있나? 있으면 가져오기
    HaveIChosenStoreVO haveIChosenStoreVO = lunchMapperInterface.haveIChosenStore((String) session.getAttribute("id"), today());
    logger.info("haveI"+haveIChosenStoreVO);
    model.addAttribute("choiceStore -> ",haveIChosenStoreVO);
    //전체 유저의 식당,사무실 리스트 가져오기
    List checkStoreListOfficeB = lunchService.getStoreListOfficeB(today());
    List checkStoreListOfficeA = lunchService.getStoreListOfficeA(today());
    
    model.addAttribute("StoreListOfficeB", checkStoreListOfficeB);
    model.addAttribute("StoreListOfficeA", checkStoreListOfficeA);
    // 리스트 넘기기
    //model.
    return "lunch";
  }
  
      /* 사무실별 식당 선택현황 */
  @RequestMapping("/lunch_officeA")
  public String lunch_OfficeA(Model model) {
    List getStoreListOfficeA = lunchService.getStoreListOfficeA(today());
    model.addAttribute("StoreListOfficeA", getStoreListOfficeA);
    return "lunch_officeA";
  }
  
  @RequestMapping("/lunch_officeB")
  public String lunch_officeThe(Model model) {
    List getStoreListOfficeB = lunchService.getStoreListOfficeB(today());
    model.addAttribute("StoreListOfficeB", getStoreListOfficeB);
    return "lunch_officeB";
  }
    /* 사무실별 식당 선택현황 */
  
  /* lunch */

"/menu" 페이지 사용되는 메소드 리스트
/submenuList같은 경우에는 사용자 입력에 의해 DB관리로 데이터가 쌓이는 방식으로 운영하려고 하였으나...
이용자들이 메뉴얼을 따라주지않아 변경... 
유저친화적으로 제작 하고 싶었지만 menmonth가 과하게 필요하여 버린 기능(변명)

  /* menu */
  @RequestMapping("/menu")
  public String menu(HttpSession session, Model model) throws Exception{
    if(session.getAttribute("id")==null){
      return "redirect:/";
    }
    // id값 넘겨주기
    model.addAttribute("id", session.getAttribute("id"));
    String first = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-08-29-00"));
    String second = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-10-19-00"));
    String last = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yy-MM-dd-13-01-00"));
    SimpleDateFormat SDF = new SimpleDateFormat("yy-MM-dd-HH-mm-ss");
    Date firstParse = SDF.parse(first);
    Date secondParse = SDF.parse(second);
    Date lastParse = SDF.parse(last);
    logger.info("secondParse -> " + secondParse);
    logger.info("lastParse -> " + lastParse);
    if (new Date().after(firstParse) && new Date().before(secondParse)) {
      return "redirect:/lunch";
    }else if(new Date().before(firstParse) || new Date().after(lastParse) ){
      return "redirect:/ready";
    }
    model.addAttribute("OfficeBStore", lunchMapperInterface.getOfficeBStoreForMenu(today()));
    model.addAttribute("OfficeAStore", lunchMapperInterface.getOfficeAStoreForMenu(today()));
    
    return "menu";
  }
  
  @RequestMapping("/mainMenuList")
  public String mainMenuList(@RequestParam String office, Model model) {
    String store = lunchMapperInterface.getDailyStore(office, today());
    List<MenuListVO> menuList = lunchMapperInterface.getMenuList(store);
    if (menuList.isEmpty()) {
      model.addAttribute("store", store);
    } else {
      model.addAttribute("menuList", menuList);
    }
    return "mainMenuList";
  }

  /* subMenuList */
  // 특이사항 : 현재 사용하지않고 있음
  @RequestMapping("/subMenuList")
  public String subMenuList(@RequestParam int menu_seq, Model model){
    logger.info("@@@@@@getSubMenuList 시작");
// submenu_seq 먼저 들고오기
    List<Integer> getSubmenuSeq = lunchMapperInterface.getSubmenuSeq(menu_seq);
    List<SubMenuListVO> subMenuList = new ArrayList<>();
    for(int submenu_seq : getSubmenuSeq){
      // 해당 메뉴의 서브메뉴 가져오기
      SubMenuListVO sVO = lunchMapperInterface.getSubMenuList(submenu_seq);
      // 서브메뉴의 서브옵션 가져오기
      sVO.setSubmenu_optionVO(lunchMapperInterface.getSubmenuOption(submenu_seq));
      System.out.println("sVO->"+sVO);
      subMenuList.add(sVO);
    }
    model.addAttribute("subMenuList", subMenuList);
    logger.info("@@@@@@getSubMenuList 끝");
    return "subMenuList";
  }
  /* subMenuList */
  
  @RequestMapping("/addMenuList")
  public String addMenuList(@RequestParam int menu_seq, Model model){
    logger.info(" Controller getAddMenuList 시작");
    List<AddMenuListVO> addMenuList = lunchMapperInterface.getAddMenuList(menu_seq);
    if(addMenuList.isEmpty()) {
      model.addAttribute("addMenuList", null);
    }
    model.addAttribute("addMenuList", addMenuList);
    logger.info(" Controller getAddMenuList 끝");
    return "addMenuList";
  }
  
  @RequestMapping("/myOrderList")
  public String myOrderList(HttpSession session, Model model) {
    logger.info("today -> "+ today());
    List<MyOrderListVO> myOrderListVO = lunchService.getMyOrderlist((String) session.getAttribute("id"), today());
    logger.info("orderList -> "+ myOrderListVO);
    if (myOrderListVO.isEmpty()) {
      model.addAttribute("myOrderList", null);
      logger.info("orderList empty-> "+ model.getAttribute("myOrderList"));
    } else {
      model.addAttribute("myOrderList", myOrderListVO);
    }
    return "myOrderList";
  }
  
  @RequestMapping("/orderList")
  public String orderList(@RequestParam String office, Model model){
    List<ChoiceMenuVO> orderList = lunchService.getOrderList(today(), office);
    if (orderList.isEmpty()) {
      model.addAttribute("orderList", null);
    } else {
      model.addAttribute("orderList", orderList);
    }
    model.addAttribute("office", office.equals("OfficeA") ? "사무실A" : "사무실B");
    return "orderList";
  }
  
  @RequestMapping("/lunchCount")
  public String lunchCount(Model model){
    logger.info("today -> "+ today());
    
    model.addAttribute("OfficeACount", lunchMapperInterface.getLunchCount(today(),"OfficeA"));
    model.addAttribute("OfficeBCount", lunchMapperInterface.getLunchCount(today(),"OfficeB"));
    model.addAttribute("noLunchCount", lunchMapperInterface.getLunchCount(today(),"noLunch"));
    return "lunchCount";
  }
  /* menu */

그외

  @RequestMapping("/ready")
  public String ready() {
    return "/ready";
  }

https://github.com/MasonBaek/springboot_PickingLunchMenu/blob/main/mrsbok/src/main/java/com/lunch/mrsbok/controller/ViewController.java

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com


VO가 담기 domain, repository mapper로 구성된 interface, service는 주소로 대체한다

https://github.com/MasonBaek/springboot_PickingLunchMenu/tree/main/mrsbok/src/main/java/com/lunch/mrsbok/domain

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com

https://github.com/MasonBaek/springboot_PickingLunchMenu/tree/main/mrsbok/src/main/java/com/lunch/mrsbok/mapper

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com

https://github.com/MasonBaek/springboot_PickingLunchMenu/tree/main/mrsbok/src/main/java/com/lunch/mrsbok/service

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com

특이사항 : 아래참조

	List<StoreVO> list = new ArrayList<>();
	list.addAll(lunchMapperInterface.getStore());
    <select id="getStore" resultType="com.lunch.mason.domain.StoreVO">
        select store
        from lunch.store
    </select>

resultType을 VO 형태로 할때 addAll을 써도된다는 포스팅을 보고 테스트로 써봄
아래와 같이 써도됨

List<StoreVO> list = new ArrayList<>(lunchMapperInterface.getStore());

query가 적힌 mapper.xml

https://github.com/MasonBaek/springboot_PickingLunchMenu/blob/main/mrsbok/src/main/resources/mapper/LunchMapper.xml

 

GitHub - MasonBaek/springboot_PickingLunchMenu

Contribute to MasonBaek/springboot_PickingLunchMenu development by creating an account on GitHub.

github.com


view + css + css img 는 5편에서