본문 바로가기
공부기록/실습

6월 2일 (1) Spring - movieinfo 2

by project100 2023. 6. 2.

페이징 처리

 

pagingutil

package com.raspberry.movieinfo.util;

import lombok.AllArgsConstructor;

@AllArgsConstructor
public class PagingUtil {
    private int totalPage; // 전체 페이지 개수
    private int pageNum;   // 현재 보이는 페이지 번호
    private int pageCnt;   // 페이지 당 보여질 번호 개수
    private String urlStr; // 링크 url

    public String makePaging(){
        String pageHtml = null;
        StringBuffer sb =  new StringBuffer();

        // 현재 그룹
        int curGroup = (pageNum % pageCnt) > 0 ? pageNum/pageCnt + 1 : pageNum/pageCnt;

        // 시작번호
        int start = (curGroup * pageCnt) - (pageCnt - 1);

        // 끝 번호
        int end = (curGroup * pageCnt) >= totalPage ? totalPage : curGroup * pageCnt;

        // page HTML 작성
        // 이전 처리
        if(start != 1){
            sb.append("<a class='pno' href='/" + urlStr + "pageNum=" + (start - 1) + "'>◁</a>");
        }
        
        // 그룹내 페이지 번호 처리
        for(int i = start; i <= end; i++){
            // 현재 페이지 번호
            if(pageNum == i){
                sb.append("<font class='pno'>" + i + "</font>");
            } else {
                sb.append("<a class='pno' href='/" + urlStr + "pageNum=" + i + "'>" + i + "</a>");
            }
        }
        
        // 다음 처리 
        // 예 <a class ='pno' href='/?pageNum=6'>▶</a>
        if (end != totalPage){
            sb.append("a class='pno' href='/" + urlStr + "pageNum=" + (end + 1) + "'>▷</a>");
        }
        
        // Stringbuffer -> String 변환
        pageHtml = sb.toString();
        
        return pageHtml;
    }
}

 

movieservice

// 페이징 용 html 작성
String paging = getPaging(pageNum, totalPage);
private String getPaging(Integer pageNum, int totalPage) {
        log.info("getPaging()");
        String pageHtml = null;
        int pageCnt = 2;
        String urlstr = "?";

        PagingUtil paging = new PagingUtil(totalPage, pageNum, pageCnt, urlstr);

        pageHtml = paging.makePaging();
        return pageHtml;
    }
// 페이징 용 html 추가
mv.addObject("paging", paging);
 

home에 링크 걸때 구분해서 걸기  

th:utext  = innerHtml - 링크로 걸때
th: text = innerText - 글자로만 출력
 

등록 버튼 처리

wirteForm.html 작성
<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Movie - write</title>
    <link rel="stylesheet" th:href="@{css/style.css}">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"
            integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
    <script th:inline="javascript">
        $(function () {
            let m = [[${msg}]]; // msg가 없으면 null
            if (m != null) {
                alert(m);
            }

            // 파일 업로드 처리 시 선택한 파일명 출력
            $("#file").on("change", function (){
                // 하나여도 무조건 배열형태
               let files = $("#file")[0].files;
               // 취소될 수도 있기 때문에 빈 문자열로 만들기
               let fileName = "";
               if(files.length == 1){
                   fileName = files[0].name;
               } else {
                   // 파일 선택창에서 '취소'버튼 클릭
                   fileName = "파일선택"; // 원래 이름으로 복원
               }
               $(".upload-name").val(fileName);
            });

            // 뒤로가기 .click / .on("click") 두가지 중 on이 더 안정적
            $("#backbtn").on("click", function (){
               let pn = [[${session.pageNum}]];
               if(pn == null){
                   pn = 1;
               }
               location.href = "/?pageNum=" + pn;
            });
        });
    </script>
</head>
<body>
<div class="wrap">
    <th:block th:insert="~{header.html}"></th:block>
    <div class="content">
        <form th:action="@{writeProc}" method="post" class="write-form" enctype="multipart/form-data">
            <h2>영화 등록</h2>
            <div class="filebox">
                <label for="file"> 포스터</label>
                <input type="file" name="files" id="file">
                <input type="text" class="upload-name" value="파일선택" readonly>
            </div>
            <input type="text" class="write-input" name="mname" autofocus placeholder="영화 제목 입력" required>
            <input type="text" class="write-input" name="mdirector" placeholder="감독 입력" required>
            <input type="text" class="write-input" name="mnation" placeholder="국가 입력" required>
            <input type="text" class="write-input" name="mgenre" placeholder="장르 입력" required>
            <input type="text" class="write-input" name="mactor" placeholder="주연배우 입력" required>
            <input type="date" class="write-input" name="mopen" placeholder="개봉일 입력" required>
            <textarea rows="5" class="write-input ta" name="msynopsis" placeholder="영화 개요 입력"></textarea>
            <div class="btn-area">
                <input type="submit" class="btn-write" value="W">
                <input type="reset" class="btn-write" value="R">
                <input type="button" class="btn-write" value="B" id="backbtn">
            </div>
        </form>
    </div>
    <th:block th:insert="~{footer.html}"></th:block>
</div>
</body>
</html>
 

movie controller

@GetMapping("writeForm")
    public String writeForm(){
        log.info("writeForm()");
        return "writeForm";
    }

    @PostMapping("writeProc")
    public String writeProc(@RequestPart List<MultipartFile> files, Movieinfo movie, HttpSession session, RedirectAttributes rttr){
        log.info("writeProc()");
        String view = mServ.insertMovie(files, movie, session, rttr);

        return view;
    }

movie serviece

public String insertMovie(List<MultipartFile> files, Movieinfo movie, HttpSession session, RedirectAttributes rttr) {
        log.info("insertMovie()");
        String view = null;
        String msg = null;

        try{
            // 파일 업로드 처리
            fileUpload(files, session, movie);
            // DB에 영화정보 저장
            mRepo.save(movie);
            // insert, update 모두 save 메소드로 처리 (주의 : update할 때 키값을 포함하여 처리 해야 한다.)
            view = "redirect:/";
            msg = "등록 성공";
       } catch (Exception e){
            e.printStackTrace();
            view = "redirect:writeForm";
            msg = "등록 실패";
        }
        rttr.addFlashAttribute("msg", msg);
        return view;
    }

    private void fileUpload(List<MultipartFile> files, HttpSession session, Movieinfo movie) throws IOException {
        log.info("fileUpload()");
        String sysname = null;
        String oriname = null; // 다운로드 할 때 필요, 현재는 파일이 업로드만 되기 때문에 없어도 됨

        // webapp 경로 구하기
        String realPath = session.getServletContext().getRealPath("/");
        realPath += "upload/";
        File folder = new File(realPath);
        if(folder.isDirectory() == false){
            folder.mkdir();
        }
        MultipartFile mf = files.get(0);
        oriname = mf.getOriginalFilename();
        if(oriname.equals("")){
            return; // 파일 업로드 안함.
        }
        sysname = System.currentTimeMillis() + oriname.substring(oriname.lastIndexOf("."));
        File file = new File(realPath + sysname);
        mf.transferTo(file);

        movie.setMoriname(oriname);
        movie.setMsysname(sysname);
    }