gi_dor

spring 게시판 글 작성 본문

First/Spring

spring 게시판 글 작성

기돌 2023. 7. 23. 15:33
728x90

Mapper

 <!--        공지사항 등록 -->
    <insert id="insert" parameterType="NoticeDTO">
        INSERT INTO notice NOTC_TP, TITLE, CONTENT, START_DTTM, END_DTTM)
        VALUES (#{notcTp}, #{title}, #{content}, #{startDttm}, #{endDttm})
    </insert>

 


DTO

 private Integer notcNo;
    private String notcTp;
    private String notcTpNm;
    private String title;
    private String content;
    private Integer viewCnt;

    private Date startDttm;
    private Date endDttm;
    private Date regDttm;
    private Integer regrId;
    private Date updDttm;
    private Integer updrId;

 

 

DAO

   @Override
    public int insert(NoticeDTO dto) throws Exception{
        return session.insert(namespace+"insert",dto);
    }

 

service

  @Override
    public int write(NoticeDTO noticeDto) throws Exception {
        return noticeDao.insert(noticeDto);
    }

 

controller

    /**
     * 새로운 공지사항을 작성한다.
     *
     * @param noticeDTO 작성할 공지사항의 정보를 담고 있는 NoticeDTO 객체
     * @param m 컨트롤러에서 뷰로 데이터를 전달하는 Model 객체
     * @param session 세션 객체를 사용하여 로그인 정보를 확인하기 위한 HttpSession 객체
     * @param rattr RedirectAttributes를 사용하여 리다이렉트 시 데이터를 전달하기 위한 객체
     * @return 공지사항 작성 결과에 따라 적절한 뷰 페이지로 리다이렉트
     *
     * redirect는 m 모델에 담으면 유효하지 않는다고함
     * flashAttributes 는 redirect 시에만 유효하고 다음 요청까지 유지 되기 때문에 메시지가 유지 된다고함
     * 솔직히 마지막 문장 무슨말인지 이해못했음.
     * 결론은 return 이아니라  return redirect: 붙으면 RedirectAttributes 써야함
     */
    @PostMapping("/write")
    public String write(NoticeDTO noticeDTO, Model m, HttpSession session, RedirectAttributes rattr) {

        try {
      
            rattr.addFlashAttribute("noticeDTO", noticeDTO);


            // 작성된 공지사항을 DB에 등록하고 처리된 행의 수를 반환
            int rowCnt = noticeService.write(noticeDTO);

            // 날짜를 모델에 추가함
            Instant startOfToday = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant();
            m.addAttribute("startOfToday", startOfToday.toEpochMilli());


            System.out.println("mbrId = " + mbrId);

            System.out.println("공지사항 종류: " + noticeDTO.getNotcTp());
            System.out.println("제목 = " + noticeDTO.getTitle());
            System.out.println("등록 날짜 = " +noticeDTO.getRegDttm());
            System.out.println("종료날짜 = " + noticeDTO.getEndDttm());
            System.out.println("시작날짜 = " + noticeDTO.getStartDttm());

            // 처리된 행의 수가 1이 아니면 예외를 발생시킴
            if (rowCnt != 1)
                throw new Exception("Write failed!!!!!!!!!!!!!");

            // 성공적으로 작성되었음을 나타내는 메시지를 FlashAttribute에 추가하여 리다이렉트 시 전달
            rattr.addFlashAttribute("msg", "WRT_OK");
            

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

            // 작성 실패한 공지사항 정보와 에러 메시지를 FlashAttribute에 추가하여 에러 페이지로 이동
            rattr.addFlashAttribute("noticeDTO", noticeDTO);
            rattr.addFlashAttribute("msg", "WRT_ERR");

            return "redirect:/adminNotice/write";


//            m.addAttribute("msg", "WRT_ERR");
//             작동하지않음 , 왜 ?
//             FlashAttribute는 리다이렉트 시에만 유효하며 다음 요청까지 유지되기 때문에 리다이렉트 이후에도 메시지가 유지됩니다.
        }

        // 성공적으로 작성되었음을 나타내는 메시지를 FlashAttribute에 추가하여 공지사항 목록으로 리다이렉트
//        return ViewPath.BOS_CS + "adminNotice/list";
        return "redirect:/adminNotice/list";
    }




    @GetMapping("/write")
    public String showWriteForm() {

        return ViewPath.BOS_CS + "adminNoticeWrite";
    }

 

write.jsp

 

form 태그 안에 있는

input에 name은 DTO에 정의되어진 대로 작성 해야함 오타 때문에 간간히 에러 발생했음.

<%@ page import="java.time.LocalDateTime" %>
<%@ page import="java.time.format.DateTimeFormatter" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt_rt" %>


<head>
  <style>
    @import url(${cssUrlBos}/cs/adminNoticeWrite.scss);
  </style>
</head>

<script>
  let msg = "${msg}";
  if (msg == "LIST_ERR") alert("게시물 목록을 가져오는데 실패했습니다. 다시 시도해 주세요.");
  if (msg == "WRT_OK") alert("성공적으로 등록되었습니다.");
  if (msg == "WRT_ERR") alert("게시물 작성 하는데 실패 했습니다.");
  // Add other messages here
</script>

<!-- Form for writing a notice -->
<div class="container">
  <h2 class="title-t ty3 mb-30">공지사항 작성</h2>

  <form id="form" class="frm" action="<c:url value='/adminNotice/write'/>" method="post">

<%--   <input type="hidden" name="notcNo" value="${noticeDTO.notcNo}">--%>

    <!-- Notice Type -->
    <div class="form-group">
      <label for="exampleSelect1" class="form-label mt-4">공지사항 종류</label>
      <select class="form-select" name = "notcTp" id="exampleSelect1">
        <option value="10"> 배송  </option>
        <option value="20"> 전체 공지 </option>
        <option value="30"> 이벤트 </option>
      </select>
    </div><br>


    <!-- Notice Title -->
    제목
    <input name="title" type="text" class="detail-tit1" placeholder="제목을 입력해 주세요." required><br>

    <!-- Notice Content -->
    상세내용
    <textarea name="content" rows="15" class="detail-cont" placeholder="내용을 입력해 주세요." required></textarea>



    <!-- Start Date -->
    공지사항 시작 날짜
    <input type="date" id = noticeCalendar name="startDttm" required>

    <!-- End Date -->
    공지사항 종료 날짜
    <input type="date" id = noticeCalendar  name="endDttm" required>




    <!-- Buttons -->
    <button type="button" id="listBtn" class="btn btn-primary btn-sm"><i class="fa-solid fa-list-ul"></i> 목록</button>
    <button type="submit" id="writeBtn" class="btn btn-primary btn-sm"><i class="fa fa-pen-nib"></i> 등록</button>
  </form>
</div>

<!-- Show success or error messages -->
<script>

  // Define button click event handlers
  $(document).ready(function() {

    <%--$('#listBtn').on("click", function() {--%>
    <%--  location.href = "<c:url value='/adminNotice/list'/>?page=${sc.page}&pageSize=${sc.pageSize}";--%>
    <%--});--%>

    $("#listBtn").on("click", function(){
      location.href="<c:url value='/adminNotice/list${searchCondition.queryString}'/>";
    });

      <%--function noticeWrite(){--%>
      <%--    location.href="<c:url value='/adminNotice/write${searchCondition.queryString}'/>";--%>
      <%--}--%>

  });

</script>

 

 


 

에러 메세지

 

ERROR: jdbc.audit - 1. PreparedStatement.execute() INSERT INTO notice (NOTC_TP, TITLE, CONTENT, START_DTTM, END_DTTM) VALUES ('10', 'asdads', 
'dasdsdsdsd', '07/23/2023 00:00:00.000', '08/05/2023 00:00:00.000') 

java.sql.SQLException: Field 'REGR_ID' doesn't have a default value

 

Mapper에 이게 필요하다는건가 ? 흠

 

Mapper - REGR_ID - 등록자 계정 ID

  <insert id="insert" parameterType="NoticeDTO">
        INSERT INTO notice (REGR_ID,NOTC_TP, TITLE, CONTENT, START_DTTM, END_DTTM)
        VALUES (#{regrId},#{notcTp}, #{title}, #{content}, #{startDttm}, #{endDttm})
    </insert>

 

Controller 

@SessionAttribute int mbrId

noticeDTO.setRegrId(mbrId);
    @PostMapping("/write")
    public String write(NoticeDTO noticeDTO, Model m, HttpSession session, RedirectAttributes rattr,@SessionAttribute int mbrId) {

        try {
            noticeDTO.setRegrId(mbrId);
            rattr.addFlashAttribute("noticeDTO", noticeDTO);


            // 작성된 공지사항을 DB에 등록하고 처리된 행의 수를 반환
            int rowCnt = noticeService.write(noticeDTO);

            // 날짜를 모델에 추가함
            Instant startOfToday = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant();
            m.addAttribute("startOfToday", startOfToday.toEpochMilli());


            System.out.println("mbrId = " + mbrId);

            System.out.println("공지사항 종류: " + noticeDTO.getNotcTp());
            System.out.println("제목 = " + noticeDTO.getTitle());
            System.out.println("등록 날짜 = " +noticeDTO.getRegDttm());
            System.out.println("종료날짜 = " + noticeDTO.getEndDttm());
            System.out.println("시작날짜 = " + noticeDTO.getStartDttm());

            // 처리된 행의 수가 1이 아니면 예외를 발생시킴
            if (rowCnt != 1)
                throw new Exception("Write failed!!!!!!!!!!!!!");

            // 성공적으로 작성되었음을 나타내는 메시지를 FlashAttribute에 추가하여 리다이렉트 시 전달
            rattr.addFlashAttribute("msg", "WRT_OK");


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

            // 작성 실패한 공지사항 정보와 에러 메시지를 FlashAttribute에 추가하여 에러 페이지로 이동
            rattr.addFlashAttribute("noticeDTO", noticeDTO);
            rattr.addFlashAttribute("msg", "WRT_ERR");

            return "redirect:/adminNotice/write";


//            m.addAttribute("msg", "WRT_ERR");
//             작동하지않음 , 왜 ?
//             FlashAttribute는 리다이렉트 시에만 유효하며 다음 요청까지 유지되기 때문에 리다이렉트 이후에도 메시지가 유지됩니다.
        }

        // 성공적으로 작성되었음을 나타내는 메시지를 FlashAttribute에 추가하여 공지사항 목록으로 리다이렉트
//        return ViewPath.BOS_CS + "adminNotice/list";
        return "redirect:/adminNotice/list";
    }

 

728x90