Language/Spring

[Spring] 게시판(Board) CRUD 구현하기

rame 2022. 9. 20. 12:24


  1. 전체 파일 경로
  2. Service 패키지 생성 및 파일 작성
  3. 게시판 리스트(Board List) 구현
  4. 게시판 CRUD Controller, JSP 파일 작성
    4-1. Create (생성)
    4-2. Read (읽기)
    4-3. Update (수정)
    4-4. Delete (삭제)

 

1. 전체 파일 경로

 

 

2. Service 패키지 생성 및 파일 작성

 - IBoardService.java 파일 작성

import java.util.List;

public interface IBoardService {
	public void create(BoardDto dto) throws Exception;
	public BoardDto read(int bno) throws Exception;
	public void delete(int bno) throws Exception;
	public void update(BoardDto dto) throws Exception;
	public List<BoardDto> listAll() throws Exception;
}

 

 

 - BoardServiceImpl.java

  IBoardService 인터페이스를 상속받는 class 파일 작성

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.human.dao.IBoardDao;
import com.human.dto.BoardDto;
@Service
public class BoardServiceImpl implements IBoardService {
	@Autowired
	private SqlSession sqlSession;
	@Override
	public void create(BoardDto dto) throws Exception {
		//추가 비지니스로직을 기술하기 위해 service 인터페이스 추가.
		IBoardDao dao=sqlSession.getMapper(IBoardDao.class);
		dao.create(dto);
	}
    
	@Override
	public BoardDto read(int bno) throws Exception {
		// TODO Auto-generated method stub
		IBoardDao dao=sqlSession.getMapper(IBoardDao.class);
		BoardDto r=dao.read(bno);
		return r;
	}

	@Override
	public void delete(int bno) throws Exception {
		// TODO Auto-generated method stub
		IBoardDao dao=sqlSession.getMapper(IBoardDao.class);
		dao.delete(bno);
	}

	@Override
	public void update(BoardDto dto) throws Exception {
		// TODO Auto-generated method stub
		IBoardDao dao=sqlSession.getMapper(IBoardDao.class);
		dao.update(dto);
	}

	@Override
	public List<BoardDto> listAll() throws Exception {
		IBoardDao dao=sqlSession.getMapper(IBoardDao.class);
		List<BoardDto> dtos=dao.listAll();
		return dtos;
	}
}

 

 

 - root-context.xml

  component-scan을 사용해 Service 어노테이션을 xml에 선언하여 사용

<context:component-scan base-package="com.human.service" />

 

 

3. 게시판 리스트(Board List) 구현

 - 파일 :  BoardController.java

@Controller
public class BoardController {
	@Inject
	private IBoardService service;
	
	@RequestMapping(value = "/board/listAll", method = RequestMethod.GET)
	public void listAll(Model model) throws Exception {
		//DB에 있는 모든데이터를 화면에 보여주기 
		//DB에 있는 모든데이터를 읽어다주는 service를 실행해서 모델의 list 에 담는다.
		model.addAttribute("list",service.listAll());
	}
}

 

 

 - 파일 : views/board/listAll.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
/*tableStart*/
#customers {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#customers td, #customers th {
  border: 1px solid #ddd;
  padding: 8px;
}
#customers tr:nth-child(even){background-color: #f2f2f2;}
#customers tr:hover {background-color: #ddd;}
#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #04AA6D;
  color: white;
}
/*tableEnd*/
</style>
<script>
var result='${msg}';
if(result=='success'){
	alert('처리가 완료되었습니다.');
}
//result는  글을 등록하고 들어오면  success가 들어 있고,
//직접들어오면 아무것도 담겨있지 않는다.

window.onload=function(){
	document.getElementsByClassName("btn")[0]
	.addEventListener("click",function(){
		location.href="/ex/board/register";
	});
}
</script>
</head>
<body>
<h1>게시판</h1>
<table boarder="1" width="90%" id="customers">
	<tr>
	<th>bno</th>
	<th>title</th>
	<th>writer</th>
	<th>regdate</th>
	<th>viewCount</th>
	</tr>
	<c:forEach items="${list }" var="boardDto">
	<tr>
		<td>${boardDto.bno }</td>
		<td><a href='/ex/board/read?bno=${boardDto.bno}'>
		${boardDto.title }</a></td>
		<td>${boardDto.writer }</td>
		<td><fmt:formatDate pattern="yyyy-MM-dd HH:mm:ss" 
		value="${boardDto.regdate }" /> </td>
		<td>${boardDto.viewcnt }</td>		
	</tr>
	</c:forEach>
</table>
<button class="btn"> 글쓰기</button>
</body>
</html>

 

 

 - 출력 화면

 

4. 게시판 CRUD Controller 및 JSP 작성

 4-1. Create (생성)

 - 파일 :  BoardController.java

@RequestMapping(value = "/board/register", method = RequestMethod.GET)
public void register(Model model) throws Exception {

}

@RequestMapping(value = "/board/register", method = RequestMethod.POST)
public String register(BoardDto boardDto, Model model, RedirectAttributes rttr) throws Exception {
    service.create(boardDto);
    rttr.addFlashAttribute("msg","success");
    return "redirect:/board/listAll";
}

 

 

 - 파일 : views/board/register.jsp

 

 

 - 출력 화면

 

 

 

tip. 한글이 나오지 않는 경우 (더보기)

더보기

파일 경로 : src/main/webapp/WEB-INF/web.xml

 

<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter
    </filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 

 

 

 

 4-2. Read (읽기)

 - 파일 :  BoardController.java

@RequestMapping(value = "/board/read", method = RequestMethod.GET)
public void read(@RequestParam("bno")int bno, Model model) throws Exception {
    model.addAttribute(service.read(bno));
    //model.addAttribute("boardDto",service.read(bno));
}

 

 

 - 파일 : views/board/read.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
window.onload=function(){
	document.getElementById('listAll').addEventListener("click", function(){
		location.href="/ex/board/listAll";
	})
	document.getElementById('remove').addEventListener("click", function(){
		location.href="/ex/board/remove?bno=${boardDto.bno}";
	})
	document.getElementById('modify').addEventListener("click", function(){
		location.href="/ex/board/modify?bno=${boardDto.bno}";
	})
}
</script>
</head>
<body>
	title:<input type="text" name=title style="width:100%" value='${boardDto.title }' readonly="readonly"><br>
	content:<textarea name=content  rows="8" style="width:100%" readonly="readonly">${boardDto.content }</textarea><br>
	writer:<input type="text" name=writer style="width:100%" value='${boardDto.writer }' readonly="readonly"><br>
	
<button id=listAll >List All</button>
<button id=remove >remove</button>
<button id=modify >modify</button>	

</body>
</html>

 

 

 - 출력 화면

 

 

 

 

 4-3. Update (수정)

 - 파일 :  BoardController.java

@RequestMapping(value = "/board/modify", method = RequestMethod.GET)
public void modify(@RequestParam("bno")int bno, Model model) throws Exception {
    model.addAttribute(service.read(bno));
    //model.addAttribute("boardDto",service.read(bno));
}

 

 

 - 파일 : views/board/modify.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
window.onload=function(){
	document.getElementById('listAll').addEventListener("click",function(){
		location.href="/ex/board/listAll";
	})
	
	document.getElementById('modify').addEventListener("click",function(){
		//document.getElementById('modifyForm').mthod="get";
		//document.getElementById('modifyForm').action="/ex/board/modify";
		document.getElementById('modifyForm').submit();
	})
}
</script>
</head>
<body>
<form id="modifyForm" method="post" action="/ex/board/modify">
	bno:<input type="text" name=bno style="width:100%"
	 value='${boardDto.bno }' readonly="readonly"><br>
	title:<input type="text" name=title style="width:100%" 
	value='${boardDto.title }' ><br>
	content:<textarea name=content  rows="8" style="width:100%"
	>${boardDto.content }</textarea><br>
	writer:<input type="text" name=writer style="width:100%" 
	value='${boardDto.writer }'><br>
</form>
<button id=modify > SAVE</button>
<button id=listAll > Cancel</button>

</body>
</html>

 

 

 - 출력 화면

 

 

 

 

 4-4. Delete (삭제)

 - 파일 :  BoardController.java

@RequestMapping(value = "/board/remove", method = RequestMethod.GET)
public String remove(@RequestParam("bno")int bno, RedirectAttributes rttr) throws Exception {
    service.delete(bno);
    rttr.addFlashAttribute("msg","success");
    return "redirect:/board/listAll";		
}

 

 

 - 출력 화면