Board 처리
0. Repository 생성
public interface BoardRepository extends CrudRepository<Board, Long> {
//페이지 처리된 목록을 가져오는 메소드
Page<Board> findByBnumGreaterThan(long bnum, Pageable pageable);
}
1. Board 입력
- BoardService.java
//게시글 저장 메소드
@Transactional //정상이면 commit, 에러발생 시 rollback 처리.
public String insertBoard(List<MultipartFile> files, //업로드 파일 목록
Board board, HttpSession session,
RedirectAttributes rttr) {
log.info("insertBoard()");
String msg = null;
String view = null;
try {
//insert와 update 처리 메소드 save()
bRepo.save(board);//저장과 동시에 select도 처리
log.info("bnum : " + board.getBnum());
//파일 저장(외래키에 해당하는 게시글 번호가 필요함.)
fileUpload(files, session, board);
view = "redirect:/";//목록 화면으로 돌아가기.
msg = "저장 성공";
} catch (Exception e){
e.printStackTrace();
view = "redirect:writeFrm";
msg = "저장 실패";
}
rttr.addFlashAttribute("msg", msg);
return view;
}
2. Board 상세
- BoardService.java
public ModelAndView getBoard(long bnum) {
log.info("getBoard()");
mv = new ModelAndView();
// 게시글 가져와서 담기
Board board = bRepo.findById(bnum).get();
mv.addObject("board", board);
// 첨부파일(목록) 가져와서 담기(외래키를 사용한 컬럼 가져오는 방법)
List<BoardFile> bfList = bfRepo.findByBfbid(board);
mv.addObject("bfList", bfList);
return mv;
}
3. Board 수정
- BoardService.java
@Transactional
public String boardUpdate(List<MultipartFile> files,
Board board, HttpSession session,
RedirectAttributes rttr) {
log.info("boardUpdate()");
String msg = null;
String view = null;
try {
bRepo.save(board); // insert, update 겸용
fileUpload(files, session, board); // 신규 파일 업로드 처리
msg = "수정 성공";
view = "redirect:detail?bnum=" + board.getBnum();
} catch (Exception e) {
e.printStackTrace();
msg = "수정 실패";
view = "redirect:updateFrm?bnum=" + board.getBnum();
}
rttr.addFlashAttribute("msg", msg);
return view;
}
4. Board 삭제
- BoardService.java
@Transactional
public String boardDelete(long bnum, HttpSession session,
RedirectAttributes rttr) {
log.info("boardDelete()");
String msg = null;
String view = null;
Board board = new Board();
board.setBnum(bnum);
String realPath = session.getServletContext().getRealPath("/");
realPath += "upload/";
List<BoardFile> bfList = bfRepo.findByBfbid(board);
try {
// 파일 삭제
for (BoardFile bf : bfList) {
String delPath = realPath + bf.getBfsysname(); // 삭제하고자 하는 파일 내용
File file = new File(delPath); // 파일 객체에 삽입
if (file.exists()) {
file.delete(); // 파일이 있으면 삭제
}
}
// 파일 정보 삭제(DB)
bfRepo.deleteByBfbid(board);
// 게시글 삭제
bRepo.deleteById(bnum);
msg = "삭제 성공";
view = "redirect:/";
} catch (Exception e) {
e.printStackTrace();
msg = "삭제 실패";
view = "redirect:detail?bnum=" + bnum;
}
rttr.addFlashAttribute("msg", msg);
return view;
}
File 처리
0. Repository 생성
public interface BoardFileRepository extends CrudRepository<BoardFile, Long> {
// 게시글(board)에 해당하는 파일 목록 가져오는 메소드
List<BoardFile> findByBfbid(Board board);
// 게시글에 해당하는 파일 목록 삭제
void deleteByBfbid(Board board);
}
1. Util 생성(Jpa_2강에서 말한 Java 내에서 HTML 처리)
@AllArgsConstructor
public class PagingUtil {
private int totalPage; // 전체 페이지의 개수
private int pageNum; // 현재 보이고 있는 페이지의 번호
private int pageCnt; // 보여질 페이지 번호의 개수
private String listName; // 게시판이 여러 개일 경우 게시판을 구분하는 url 지정.
//페이징용 html 코드를 만드는 메소드
public String makePaging() {
String pageHtml = null;
StringBuffer sb = new StringBuffer();
// 1. 현재 페이지가 속한 그룹 구하기
// 한 페이지에 보일 페이지 번호가 5개일 때
// [이전] 6 7 8 9 10 [다음] - 6,7,8,9,10번이 한 그룹.
int curGroup = (pageNum % pageCnt) > 0 ?
pageNum / pageCnt + 1 :
pageNum / pageCnt;
// 2. 현재 보이는 페이지 그룹의 시작 번호 구하기
// 위의 예일 경우 6을 구함.(이전 페이지는 5)
int start = (curGroup * pageCnt) - (pageCnt - 1);
// 3. 현재 보이는 페이지 그룹의 마지막 번호 구하기
// 위의 예일 경우 10을 구함.(다음 페이지는 11)
int end = (curGroup * pageCnt) >= totalPage ?
totalPage : curGroup * pageCnt;
// paging용 HTML 태그 작성
// 1. 이전 버튼 처리
if(start != 1) {// 첫 페이지에서는 [이전] 버튼을 출력하지 않음.
sb.append("<a class='pno' href='/" + listName +
"pageNum=" + (start - 1) + "'>");
sb.append(" 이전 </a>");
} // <a class='pno' href='/?pageNum=5'> 이전 </a>
// 2. 그룹 내 페이지 번호 처리
for(int i = start; i <= end; i++){
// 보여질 페이지 번호 처리(링크가 없는 페이지번호)
if(pageNum == i){
sb.append("<font class='pno' style='color: red;'>");
sb.append(" " + i + " </font>");
} // <font class='pno' style='color: red;'> 3 </font>
else {
// 링크가 붙는 페이지 번호
sb.append("<a class='pno' href='/" + listName +
"pageNum=" + i + "'>");
sb.append(" " + i + " </a>");
} // <a class='pno' href='/?pageNum=1'> 1 </a>
} // for end
// [다음] 버튼 처리
if(end != totalPage){
sb.append("<a class='pno' href='/" + listName +
"pageNum=" + (end + 1) + "'>");
sb.append(" 다음 </a>");
} // <a class='pno' href='/?pageNum=11'> 다음 </a>
// StringBuffer에서 작성한 문장을 문자열로 변환
pageHtml = sb.toString();
return pageHtml;
}
}
2. 파일 업로드
- BoardService.java
private void fileUpload(List<MultipartFile> files,
HttpSession session, Board board)
throws Exception {
log.info("fileUpload()");
// 파일 저장 위치 지정. session을 활용
String realPath = session.getServletContext().getRealPath("/");
log.info("realPath : " + realPath);
// 파일 업로드용 폴더를 자동으로 생성하도록 처리
// 업로드용 폴더 : upload
realPath += "upload/";
File folder = new File(realPath);
if(folder.isDirectory() == false){//폴더가 없을 경우 실행.
folder.mkdir();//폴더 생성 메소드
}
for(MultipartFile mf : files){
String orname = mf.getOriginalFilename();//업로드 파일명 가져오기
if(orname.equals("")){
// 업로드하는 파일이 없는 상태.
return;//파일 저장 처리 중지!
}
//파일 정보를 저장(to boardfiletbl)
BoardFile bf = new BoardFile();
bf.setBfbid(board);
bf.setBforiname(orname);
String sysname = System.currentTimeMillis() + orname.substring(orname.lastIndexOf("."));
bf.setBfsysname(sysname);
//업로드하는 파일을 upload 폴더에 저장.
File file = new File(realPath + sysname);
//파일 저장(upload 폴더)
mf.transferTo(file);
//파일 정보를 DB에 저장
bfRepo.save(bf);
}
}
3. Board + Paging 처리
- BoardService.java
public ModelAndView getBoardList(Integer pageNum, HttpSession session){
log.info("getBoardList()");
mv = new ModelAndView();
if(pageNum == null){ // 처음에 접속했을 때는 pageNum이 넘어오지 않는다.
pageNum = 1;
}
int listCnt = 5; // 페이지 당 보여질 게시글의 개수.
// 페이징 조건 생성
Pageable pb = PageRequest.of((pageNum - 1), listCnt, Sort.Direction.DESC, "bnum");
Page<Board> result = bRepo.findByBnumGreaterThan(0L, pb);
List<Board> bList = result.getContent();
int totalPage = result.getTotalPages(); // 전체 페이지 개수
String paging = getPaging(pageNum, totalPage);
mv.addObject("bList", bList);
mv.addObject("paging", paging);
// 현재 보이는 페이지의 번호를 저장
session.setAttribute("pageNum", pageNum);
return mv;
}
4. Paging 처리
private String getPaging(int pageNum, int totalpage) {
String pageHTML = null;
int pageCnt = 2; // 보여질 페이지 번호 개수(조정 가능)
String listName = "?";
PagingUtil paging = new PagingUtil(totalpage, pageNum, pageCnt, listName);
pageHTML = paging.makePaging();
return pageHTML;
}