💡 핵심 요약 (TL;DR)
스프링게시판3: 글쓰기, 글 전체 목록 조회의 동작 원리를 이해하고 실제 프로젝트에 적용하기 위한 실무 가이드다.
* method 속성은 배열로 지정 가능하다. 한 번에 여러가지 속성값(ex get, post 둘다)을 사용가능을 적용할 수 있다.
BoardController.java 코드 추가
method 속성은 배열로 지정 가능하다. 한 번에 여러가지 속성값(ex get, post 둘다)을 사용가능
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 package com.itwiilbs.controller;import java.util.List;import javax.inject.Inject;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.mvc.support.RedirectAttributes;import com.itwillbs.domain.BoardVO;import com.itwillbs.service.BoardService;@Controller @RequestMapping("/board/*") public class BoardController { private static final Logger l = LoggerFactory.getLogger(BoardController.class); @Inject private BoardService service; @RequestMapping(value = "/register", method = RequestMethod.GET) public void registerGET () throws Exception{ l.info("C: register 겟 메서드 " ); } @RequestMapping(value = "/register", method = RequestMethod.POST) public String registerPOST (BoardVO vo, RedirectAttributes rttr) throws Exception{ l.info("C: register 포스트 메서드 " +vo); System.out.println("C: register 포스트 메서드 " +vo); service.regist(vo); rttr.addFlashAttribute("result" , "success" ); rttr.addFlashAttribute("isRegist" , "true" ); return "redirect:/board/listAll" ; } @RequestMapping(value = "/listAll", method = RequestMethod.GET) public void listAll (@ModelAttribute("result") String result,Model model) throws Exception{ List <BoardVO> boardList = service.listAll(); l.info("C: listAll 겟 메서드" +boardList); model.addAttribute("boardList" , boardList); } }
register.jsp 뷰 연결1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../include/header.jsp" %> <section class ="content" > <div class ="row" > <div class ="col-md-12" > <div class ="box box-primary" > <div class ="box-header" > <h3 class ="box-title" > ITWILL 게시판</h3 > </div > <form action ="" role ="form" method ="post" > <div class ="box-body" > <div class ="form-group" > <label for ="exampleInputEmail" > 제목</label > <input type ="text" name ="title" class ="form-control" placeholder ="제목을 입력하시오" > </div > <div class ="form-group" > <label for ="exampleInputEmail" > 내용</label > <textarea name ="content" rows ="5" class ="form-control" placeholder ="내용을 입력하시오" > </textarea > </div > <div class ="form-group" > <label for ="exampleInputEmail" > 글쓴이</label > <input type ="text" name ="writer" class ="form-control" placeholder ="글쓴이를 입력하시오" > </div > </div > <div class ="box-footer" > <button type ="submit" class ="btn btn-primary" > 글 등록</button > </div > </form > </div > </div > </div > </section > </div > <%@ include file="../include/footer.jsp" %>
success.jsp 뷰 연결
문제 : 새로고침하는 순간 동일한 글이 계속 DB에 생성된다.(중복 글쓰기발생) => 동일한 글이 게시판에 도배된다.
해결 : 페이지이동을 시킨다 to listAll.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ include file="../include/header.jsp" %> <section class ="content" > <div class ="row" > <div class ="col-md-12" > <div class ="box box-primary" > <div class ="box-header" > <h3 class ="box-title" > 게시판 글쓰기 성공</h3 > </div > <div class ="box-body" > <h2 > 글쓰기 성공</h2 > ${vo } </div > <div class ="box-footer" > <h2 > 글쓰기 성공 footer</h2 > </div > </div > </div > </div > </section > </div > <%@ include file="../include/footer.jsp" %>
listAll.jsp 뷰 연결
jstl로 foreach사용하면 List 출력가능
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ include file="../include/header.jsp" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <section class ="content" > <div class ="row" > <div class ="col-md-12" > <div class ="box box-primary" > <div class ="box-header" > <h3 class ="box-title" > 게시판 글 조희</h3 > </div > <div class ="box-body" > <table class ="table table-bodered" > <tr > <th > 번호</th > <th > 글쓴이</th > <th > 제목</th > <th > 내용</th > <th > 작성일</th > <th > 조회수</th > </tr > <c:forEach var ="i" items ="${boardList }" > <tr > <td > ${i.bno }</td > <td > ${i.writer }</td > <td > <a href ="/board/read?bno=${i.bno }" > ${i.title }</a > </td > <td > ${i.content }</td > <td > <fmt:formatDate value ="${i.regdate }" pattern ="yyyy-MM-dd (E) HH:mm" /> </td > <td > <span class ="badge bg-red" > ${i.viewcnt }</span > </td > </tr > </c:forEach > </table > </div > <div class ="box-footer" > <h3 > </h3 > </div > </div > </div > </div > </section > </div > <script type ="text/javascript" > let result="${result}" ; let isResist = "${isRegist}" ; if (result == 'success' && isResist == 'true' ){ alert ('성공적으로 글 작성되었습니다.' ); }else if (result == 'success' && isResist != 'true' ){ alert ('글쓰기가 실패하였습니다.' ); }else { } </script > <%@ include file="../include/footer.jsp" %>
BoardService.java 인터페이스에 메서드 추가1 2 3 4 5 6 7 8 9 10 11 12 13 package com.itwillbs.service;import java.util.List;import com.itwillbs.domain.BoardVO;public interface BoardService { public void regist (BoardVO vo) throws Exception; public List <BoardVO> listAll () throws Exception; }
BoardServiceImpl.java 메서드 오버라이딩 코드 추가1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package com.itwillbs.service;import java.util.List;import javax.inject.Inject;import org.springframework.stereotype.Service;import com.itwillbs.domain.BoardVO;import com.itwillbs.persistence.BoardDAO;@Service public class BoardServiceImpl implements BoardService { @Inject private BoardDAO bdao; @Override public void regist (BoardVO vo) throws Exception { bdao.create(vo); System.out.println("S: regist메서드 " +vo); } @Override public List <BoardVO> listAll () throws Exception { List <BoardVO> boardList = bdao.listAll(); System.out.println("S: listAll메서드 " ); return boardList; } }
BoardDAO.java 인터페이스에 메서드 추가1 2 3 4 5 6 7 8 9 10 11 12 13 package com.itwillbs.persistence;import java.util.List;import com.itwillbs.domain.BoardVO;public interface BoardDAO { public void create (BoardVO vo) throws Exception; public List <BoardVO> listAll () throws Exception; }
BoardDAOImpl.java 메서드 오버라이딩 코드 추가1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 package com.itwillbs.persistence;import java.util.List;import javax.inject.Inject;import org.apache.ibatis.session.SqlSession;import org.springframework.stereotype.Repository;import com.itwillbs.domain.BoardVO;@Repository public class BoardDAOImpl implements BoardDAO { @Inject private SqlSession session; private static final String namespace = "com.itwillbs.mapper.BoardMapper" ; @Override public void create (BoardVO vo) throws Exception { session.insert(namespace+".create" , vo); System.out.println("DAO: 글쓰기메서드" ); } @Override public List <BoardVO> listAll () throws Exception { System.out.println("DAO: 글전체목록 메서드" ); return session.selectList(namespace+".listAll" ); } }
BoardMapper.xml SQL쿼리 추가
글 전체목록 조회시 DB에서 데이터를 꺼낼때 LIST형식으로 꺼낼 수 없고 컬럼단위로 저장되는 VO로 꺼내야한다. => resultType="com.itwillbs.domain.BoardVO"
resultType="com.itwillbs.domain.BoardVO"을 자주 쓸텐데 매번 반복해야해서 번거롭다 => Mybatis-config.xml에 typeAliases태그를 추가한다.
실무에서 글 전체목록 쿼리 중 where bno>0 가 문제가 될 수 있다. Mapper는 xml형식으로 부등호를 닫는 태그로 인식할 수 있기에 <![CDATA[]]>를 이용한다.
CDATA위치는 상관없다.
쿼리전체를 묶기도하고 에러발생부분만(where bno>0)을 묶기도 한다
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace ="com.itwillbs.mapper.BoardMapper" > <insert id ="create" > insert into tbl_board (title,content,writer) values (#{title},#{content},#{writer}) </insert > <select id ="listAll" resultType ="BoardVO" > <![CDATA[ select * from tbl_board where bno > 0 order by bno desc, regdate desc ]]> </select > </mapper >
Mybatis-config.xml 코드 추가
1 2 3 4 5 6 7 8 9 10 11 <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd" > <configuration > <typeAliases > <package name ="com.itwillbs.domain" /> </typeAliases > </configuration >
#TIL ITWILL(JAVA)