[SpringBoot] 간단한 게시판 생성_글등록
프로젝트 생성
Dependencies 추가
- Spring Web
- Spring Data JPA
- MysqlDB Driver
- Thymeleaf
- Lombok
Generate 후 zip 파일 압축 풀고 IntelliJ에서 Open Folder로 열어줌
Application.java 파일 확인
프로젝트와 데이터베이스 연결
경로 : /src/main/resources/application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/yse_spring_mvc
spring.datasource.username=root
spring.datasource.password=1234
1. 게시판 작성폼 이동
1) controller
@Controller
public class BoardController {
@Controller 어노테이션을 통해 controller임을 선언
@GetMapping("/board/write")
public String boardWriteForm(){
return "boardwrite";
}
@GetMapping : 주소와 매핑
2) view (html)
<form action="/board/writedo" method="post">
<label for="title">Name</label>
<input type="text" id="title" name="title"><br>
<label for="content">content</label><br>
<textarea id="content" name="content"></textarea>
<button type="submit">작성</button>
</form>
text, textarea 내용 POST방식으로 전송
text name은 title, textarea name은 content로 추가
button type으로 submit 선언해야 form 내용이 action 설정 경로로 이동
2. 게시물 작성
1) entity
@Entity
@Data
public class Board {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String content;
}
Entity 테이블 의미, 클래스 명이 DB 테이블 의미
@Data(변수로 id, title, content를 받게함)
@Id : primary key를 의미
@GeneratedValue(strategy = GenerationType.IDENTITY) : strategy를 GenerationType.IDENTITY로 해준다.
2) repository (db에 저장)
@Repository
public interface BoardRepository extends JpaRepository<Board, Integer> {
}
@Repository를 추가해서 레포지토리라고 지정
JPARepository를 상속하고 <>사이에 board의 타입, Id 사용한다고 작성 -> Board, Integer를 넣음
3) Service
@Service
public class BoardService {
@Autowired
private BoardRepository boardRepository;
// 글 작성
public void write(Board board){
boardRepository.save(board);
}
}
@Service를 추가해 서비스 파일로 지정
@Autowired : 객체 생성해 줄 필요없이 사용가능 (의존성 주입)
BoardRepository 인터페이스 선언
write 메소드 : Board 타입 board 매개변수 -> boardRepository.save 변수로 넘김
4) controller
@Autowired
private BoardService boardService;
@PostMapping("/board/writedo")
public String boardWritePro(Board board){
boardService.write(board);
return "";
}
BoardService class Autowired를 통해 선언
https://minddokddok.tistory.com/31?category=1040940
스프링 부트(Spring Boot)로 간단한 게시판 만들기 - 2
이전 단계를 따라했다면, 프로젝트 생성을 할 차례이다. 2) 프로젝트 생성 - IntelliJ Community에서 Spring Boot 프로젝트 생성 아래 스프링 부트 시작사이트에서 설정을 거친 후 프로젝트 생성이 가능하
minddokddok.tistory.com
위에 해당 글을 참고하였습니다.