하나씩 차근차근
article thumbnail

이번 포스트에서는 질문을 등록하는 기능을 만들어보겠습니다.

 

시작

먼저 메인 페이지에서 질문 등록하기 버튼을 만들어서 질문 등록 페이지로 이동할 수 있도록 하겠습니다.

<html layout:decorate="~{layout}">
	<div layout:fragment="content" class="container my-3">
		<table class="table">
			...
		</table>
		<a th:href="@{/question/create}" class="btn btn-primary">질문 등록하기</a>
	</div>
</html>

메인페이지인 question_list.html 파일 안에 질문 등록하기 버튼을 추가합니다.

이 버튼을 클릭하면 get 방식으로 localhost:8080/question/create 로 이동하게 됩니다.

 

질문 등록 페이지

다음으로 질문을 등록할 수 있는 페이지인 question_form.html 파일을 templates 폴더 안에 만들어줍니다.

앞에서 만든 layout.html 을 상속해서 작성을 합니다.

<html layout:decorate="~{layout}">
	<div layout:fragment="content" class="container">
		<h5 class="my-3 border-bottom pb-2">질문등록</h5>
		<form th:action="@{/question/create}" method="post">
			<div class="mb-3">
				<label for="subject" class="form-label">제목</label>
				<input type="text" name="subject" id="subject" class="form-control">
			</div>
			<div class="mb-3">
				<label for="content" class="form-label">내용</label>
				<textarea name="content" id="content" class="form-control" rows="10"></textarea>
			</div>
			<input type="submit" value="등록하기" class="btn btn-primary my-2">
		</form>
	</div>
</html>

th:action="@{/question/create}" 을 통해 버튼을 클릭하면 post 방식으로 localhost:8080/question/create 로

작성한 제목과 내용을 보내게 됩니다. 

 

컨트롤러 작성

다음으로 컨트롤러에 get방식과 post 방식으로 /question/create 로 접속했을때 처리해주는 기능을 작성하겠습니다.

package com.crud.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.crud.model.Question;
import com.crud.repository.QuestionRepository;
import com.crud.service.QuestionService;

@Controller
public class QuestionController {
	
	@Autowired
	private QuestionService questionService;

    ...

	@GetMapping("/question/create")
	public String questionCreate() {
		return "question_form";
	}
	
	@PostMapping("question/create")
	public String questionCreate(@RequestParam String subject, @RequestParam String content) {
		return "redirect:/question/list";
	}
}

위와 같이 GetMapping 과 PostMapping 을 통해 기능을 추가합니다.

questionCreate 의 인자의 경우 @RequestParam 을 통해 post 방식으로 전달되는 값을 받고 있는데

이때 변수의 이름은 question_form 파일의 input 과 textarea 의 name 과 같아야합니다.

 

서비스 작성

다음으로 post 로 전달받은 subject 와 content 의 값을 데이터베이스에 저장하는 기능을 만들어보겠습니다.

package com.crud.service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.crud.model.Question;
import com.crud.repository.QuestionRepository;

@Service
public class QuestionService {

	@Autowired
	private QuestionRepository questionRepository;
	
	...
	
	public void create(String subject, String content) {
		Question q = new Question();
		q.setSubject(subject);
		q.setContent(content);
		q.setCreateDate(LocalDateTime.now());
		questionRepository.save(q);
	}
}

위와 같이 create 메서드를 작성해서 Question 객체에 subject, content 그리고 현재 시간을 넣어서

questionRepository 의 save 메서드를 통해 저장합니다.

	@PostMapping("question/create")
	public String questionCreate(@RequestParam String subject, @RequestParam String content) {
		questionService.create(subject, content);
		return "redirect:/question/list";
	}

작성한 QuestionService 의 create 메서드를 questionController 의 questionCreate 에서 사용해서

post 방식으로 전달된 값을 저장합니다.

위와 같이 제목과 내용을 입력하고 mysql 을 확인해보면 값이 저장된것을 볼 수 있습니다.

MariaDB [springboot_crud]> select * from question;
+----+---------------------------------------+---------------------+--------------------+
| id | content                               | create_date         | subject            |
+----+---------------------------------------+---------------------+--------------------+
|  1 | hello this is first test content      | NULL                | first test subject |
|  2 | hello, this is second content thanks. | 2023-01-18 14:27:50 | hello              |
+----+---------------------------------------+---------------------+--------------------+
2 rows in set (0.000 sec)

또한 메인 페이지로 접속하면 작성한 질문 게시글이 보입니다.

profile

하나씩 차근차근

@jeehwan_lee

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!