영화 등록 페이지를 생성하고 쓰기
, 초기화
, 뒤로가기
버튼 기능을 구현한다.
컨트롤러에서는 영화 정보 등록 폼 이동, 등록 처리 맵핑처리를 한다.
영화 정보에 들어갈 컨텐츠 : 영화 포스터, 제목, 감독, 국가, 장르, 주연배우, 개봉일, 영화 줄거리
버튼 : W
- 쓰기 , R
- 초기화 , B
- 뒤로가기
@GetMapping("writeForm")
public String writeForm(){
log.info("writeForm()");
return "writeForm";
}
@PostMapping("writeProc")
public String writeProc(@RequestPart List<MultipartFile> files, Movie movie, HttpSession session, RedirectAttributes rttr){
log.info("writeProc()");
String view = mServ.insertMovie(files, movie, session, rttr);
return view;
}
⭐⭐ 헷갈릴 때 읽어보기 : RequestBody vs RequestPart vs RequestParam vs ModelAttribute
<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><!--content-->
writeForm.html
에서 입력받은 input값은 Movie
entity에서 설정한 컬럼명과 동일하게 입력한다.
예) mname, mdirector, mnation ...
public String insertMovie(List<MultipartFile> files, Movie movie, HttpSession session, RedirectAttributes rttr) {
log.info("insertMovie()");
String view = null;
String msg = null;
//업로드하는 파일의 이름을 먼저 꺼낸다.
String upFile = files.get(0).getOriginalFilename();
try{
//파일 업로드 처리
if(!upFile.equals("")) {
fileUpload(files, session, movie);
}
//DB에 영화정보 저장
mRepo.save(movie);
//insert, update 모두 save 메소드로 처리
view = "redirect:/";
msg = "등록 성공";
} catch (Exception e){
e.printStackTrace();
view = "redirect:writeForm";
msg = "등록 실패";
}
rttr.addFlashAttribute("msg", msg);
return view;
}
아래는 영화 등록할 때 사용되는 파일 업로드 처리 메소드 (insertMovie
메소드에서 사용)
private void fileUpload(List<MultipartFile> files, HttpSession session, Movie movie) throws IOException {
log.info("fileUpload()");
String sysname = null;
String oriname = null;
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();
sysname = System.currentTimeMillis()
+ oriname.substring(oriname.lastIndexOf("."));
File file = new File(realPath + sysname);
mf.transferTo(file);
movie.setMoriname(oriname);
movie.setMsysname(sysname);
}
@GetMapping("/")
public ModelAndView home(Integer pageNum, HttpSession session){
log.info("home()");
//서비스 만들면 수정할 것
//mv = new ModelAndView();
mv = mServ.getMovieList(pageNum, session);
mv.setViewName("home");
return mv;
}
영화 정보 목록은 메인 페이지에서 보여주므로 메인페이지 /
에서 getMovieList
서비스 메소드로 처리한다.
public ModelAndView getMovieList(Integer pageNum, HttpSession session){
log.info("getMovieList()");
if(pageNum == null){
pageNum = 1;
}
int listCnt = 5; //한페이지 당 5개씩 목록 출력
//페이징 조건 생성(Pageable)
Pageable pb = PageRequest.of((pageNum -1), listCnt, Sort.Direction.DESC, "mcode");
//of(시작번호, 목록개수, 정렬방식, 키필드명)
Page<Movie> result = mRepo.findByMcodeGreaterThan(0L, pb); //Long 타입이라 0L입력
//페이지 형태의 결과를 목록형태로 변환
List<Movie> mList = result.getContent();
//전체 페이지
int totalPage = result.getTotalPages();
//페이징용 html 작성
String paging = getPaging(pageNum, totalPage);
//세션에 페이지 번호 저장
session.setAttribute("pageNum", pageNum);
mv = new ModelAndView();
mv.addObject("mList", mList);
//페이징용 html 추가
mv.addObject("paging", paging);
//뷰네임 지정
mv.setViewName("home");
return mv;
}
영화 정보 리스트 불러온 모습
2023.06.26 작성