Published 2022. 8. 3. 16:12
이전글 보기
https://aamoos.tistory.com/679
목표
- 간단하게 글등록시 필수항목 영역(타이틀)을 입력하지않으면 화면에 메시지를 표출합니다.
Validation 설정방법
https://aamoos.tistory.com/662
BoardDto.java
package jpa.board.dto;
import com.querydsl.core.annotations.QueryProjection;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import java.time.LocalDateTime;
/**
* packageName : jpa.board.dto
* fileName : BoardDto
* author : 김재성
* date : 2022-08-02
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2022-08-02 김재성 최초 생성
*/
@Data
public class BoardDto {
private Long id; //시퀀스
@NotEmpty(message = "제목은 필수입니다.")
private String title; //제목
private String content; //내용
private LocalDateTime regDate; //등록 날짜
private LocalDateTime uptDate; //수정 날짜
private Long viewCount; //조회수
private String username; //사용자 이름
public BoardDto(){
}
@QueryProjection
public BoardDto(Long id, String title, String content, LocalDateTime regDate , LocalDateTime uptDate, Long viewCount, String username){
this.id = id;
this.title = title;
this.content = content;
this.regDate = regDate;
this.uptDate = uptDate;
this.viewCount = viewCount;
this.username = username;
}
}
BoardController.java
package jpa.board.controller;
import jpa.board.dto.BoardDto;
import jpa.board.entity.Board;
import jpa.board.repository.BoardRepository;
import jpa.board.repository.CustomBoardRepository;
import jpa.board.service.BoardService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
/**
* packageName : jpa.board.controller
* fileName : BoardController
* author : 김재성
* date : 2022-08-01
* description :
* ===========================================================
* DATE AUTHOR NOTE
* -----------------------------------------------------------
* 2022-08-01 김재성 최초 생성
*/
@Controller
@RequiredArgsConstructor
public class BoardController {
private final CustomBoardRepository customBoardRepository;
private final BoardService boardService;
/**
* @methodName : list
* @date : 2022-08-02 오후 2:07
* @author : 김재성
* @Description: 게시판 목록화면
**/
@GetMapping("/")
public String list(String searchVal, Pageable pageable, Model model){
Page<BoardDto> results = customBoardRepository.selectBoardList(searchVal, pageable);
model.addAttribute("list", results);
model.addAttribute("maxPage", 5);
model.addAttribute("searchVal", searchVal);
pageModelPut(results, model);
return "board/list";
}
/**
* @methodName : pageModelPut
* @date : 2022-08-02 오후 4:36
* @author : 김재성
* @Description: pagenation 관련 값 model 넣기
**/
private void pageModelPut(Page<BoardDto> results, Model model){
model.addAttribute("totalCount", results.getTotalElements());
model.addAttribute("size", results.getPageable().getPageSize());
model.addAttribute("number", results.getPageable().getPageNumber());
}
/**
* @methodName : write
* @date : 2022-08-02 오후 2:07
* @author : 김재성
* @Description: 게시판 글쓰기화면
**/
@GetMapping("/write")
public String write(Model model){
model.addAttribute("boardDto", new BoardDto());
return "board/write";
}
/**
* @methodName : save
* @date : 2022-08-03 오후 2:15
* @author : 김재성
* @Description: 게시판 글 등록
**/
@PostMapping("/write")
public String save(@Valid BoardDto boardDto, BindingResult result){
//유효성검사 걸릴시
if(result.hasErrors()){
return "board/write";
}
boardService.saveBoard(boardDto);
return "redirect:/";
}
/**
* @methodName : update
* @date : 2022-08-02 오후 2:07
* @author : 김재성
* @Description: 게시판 수정화면
**/
@GetMapping("/update")
public String update(){
return "board/update";
}
@PostMapping("/delete")
public String delete(@RequestParam List<String> boardIds){
for(int i=0; i<boardIds.size(); i++){
Long id = Long.valueOf(boardIds.get(i));
boardService.deleteBoard(id);
}
return "redirect:/";
}
}
- write, save 메소드 부분을 수정하였습니다. 저장시 @Valid에서 유효성 체크후 오류가 나는 항목을 return 합니다.
write.html
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout/default_layout}">
<head layout:fragment="css">
<style>
.fieldError {
border-color: #bd2130;
}
.form-group p{
color: red;
}
</style>
</head>
<div layout:fragment="content" class="content">
<form th:action th:object="${boardDto}" method="post">
<article>
<div class="container" role="main">
<div class="form-group">
<label for="title">제목</label>
<input type="text" class="form-control" id="title" name="title" placeholder="제목을 입력해 주세요" th:class="${#fields.hasErrors('title')}? 'form-control fieldError' : 'form-control'">
<p th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Incorrect date</p>
</div>
<br>
<div class="mb-3">
<label for="reg_id">작성자</label>
<input type="text" class="form-control" id="reg_id" name="regId" value="관리자" readonly>
</div>
<br>
<div class="mb-3">
<label for="content">내용</label>
<textarea class="form-control" rows="5" id="content" name="content" placeholder="내용을 입력해 주세요"></textarea>
</div>
<br>
<br>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="btnSave">저장</button>
<button onclick="location.href='/'" type="button" class="btn btn-sm btn-primary" id="btnList">목록</button>
</div>
</div>
</article>
</form>
</div>
</html>
<script>
</script>
- html에서 유효성검사 체크 결과 메시지를 표현합니다.
결과화면
- 글등록하기 개발이 완료가 되었습니다. 다음장에는 글 상세 페이지 수정하기를 해보겠습니다.
다음글 보기
https://aamoos.tistory.com/681