[Spring Boot] 게시물 사이트 제작하기 (1) - create / list / detail

김광일·2024년 9월 4일
0

SpringBoot

목록 보기
4/19
post-thumbnail

[1] 기초 세팅

1) boardController.java 생성

package com.example.demo.controller.page;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("")
@Controller
public class DefaultController {
    @GetMapping({"/index"})
    public String index() {
        return "index";
    }
}

2) templates 폴더에 board 폴더 생성, create.html 파일 생성

<!DOCTYPE html>
<html>
<head>
    <title>타이틀</title>
</head>
<body>
create page입니다.
</body>
</html>


: 결과

* url에 있는 값을 변수로 받아 올 수 있는 기능 (in BoardController.java)

* PathVariable을 여러 개 사용할 수 있다. (in BoardController.java)


[2] Creat.html 코드 수정하기 (입력 input, Button)

Creat.html

<!DOCTYPE html>
<html>
<head>
    <title>타이틀</title>
</head>
<body>
  create page입니다.

  <div>
      글 입력 테스트
  </div>

  제목
  <input type = "text" id = "create_board_title"/>
  내용
  <input type = "text" id = "create_board_content"/>
  작성자
  <input type = "text" id = "create_board_author"/>

  <button onclick="create_board()">저장</button>
  <button onclick="change_html()">글 바꿔보기!</button>
</body>
</html>

* ajax란?

jqeury에서 사용하는 서버와의 통신 기술

  • https://releases.jquery.com 사이트의 jQuery 3의 uncompressed를 눌러서 복사
  • 아래의 코드를 <body> 태그 안에 추가한다. (<head>에 넣어도 된다.)
    <script   src="https://code.jquery.com/jquery-3.7.1.js"   integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="   crossorigin="anonymous"></script>

[3-1] BoardRestController.java 내용 수정하기


	List<Map<String, Object>> boardList = new ArrayList<>(); // 입력 데이터를 저장하는 List

    @GetMapping({"/create"})
    public Map<String, Object> create(@RequestParam Map<String, Object> params) {
        // 세 가지의 값을 params으로부터 가져온다.
        String title = (String) params.get("title");
        String content = (String) params.get("content");
        String author = (String) params.get("author");
        int order = boardList.size(); // 일련 번호 (몇 번째 게시물인지)

        Map<String, Object> boardMap = new HashMap<>();
        boardMap.put("title", title);
        boardMap.put("content", content);
        boardMap.put("author", author);
        boardMap.put("order", ++order);

        boardList.add(boardMap);

        System.out.println(boardList); // 정상적으로 입력되었는지 확인.

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("resultCode", 200);

        return resultMap;
    }

: create 메소드를 선언함으로써, /api/board/create 경로의 get 요청 API를 제공한다.

[3-2] Creat.html 코드에서 두 개 함수 추가하기

1) change_html : 입력한 내용을 바탕으로 html 태그의 내용 바꾸는 함수

    function change_html() {
        // $("#div_id").html("바꾸고 싶은 글자!");

        let create_board_title = $("#create_board_title").val();
        // id가 create_boart_title인 html tag를 찾아 해당 태그의 value을 변수에 저장한다.
        $("#div_id").html(create_board_title);
        // create_board_title 변수에 저장된 내용으로 id가 div_id인 html tag의 값으로 바꾼다.
    }


: 결과 화면 (제목의 input에 입력된 내용을 바꿔준다.)


2) creat_board() : 입력한 값을 추가하는 함수

    function create_board(){
        $.ajax({
          	// 요청 URL
            url : "/api/board/create", 
          
 	        // 요청 방식
            type : "GET", 
          
          	// 요청 데이터
            contentType : 'application/json; charset=utf-8',
            data : {
                title : $("#create_board_title").val(),
                content : $("#create_board_content").val(),
                author : $("#create_board_author").val()
            },
          
          	// 동기식 or 비동기식 (false 시 비동기, ture 시 동기)
            cache : false, 
          
          	// 성공 시 처리할 logic
            success : (obj_data, status, xhr) => {
                alert(JSON.stringify(obj_data));
            },
          
          	// error 발생 시 처리할 logic
            error: (obj_data, status, error) => {
                alert("error!!");
                alert(JSON.stringify(obj_data));
            }
        })
    }

결과 화면


: 결과 화면 (정상적으로 작동 시 ajax로부터 받은 "200" String을 alert로 띄운다.)

[4] list page에서 전체 내용 불러오기

1) BoardRestController.java 내용 수정하기

    @GetMapping({"/list"})
    public List<Map<String, Object>> list() {
        return boardList;
    }

: /api/board/list로 get 요청이 왔을 때 처리할 함수 (boardList의 전체 내용을 반환)

2) list.html 코드 작성하기

<!DOCTYPE html>
<html>
<head>
    <title>타이틀</title>
</head>
<body>
list page입니다.

<div id = "div_list_board">
</div>


<button onclick="list_board()">글 전체 목록</button>
<script>

    function list_board(){
        $.ajax({
            url : "/api/board/list",
            type : "GET",
            contentType : 'application/json; charset=utf-8',
            data : {},
            cache : false,
            success : (obj_data, status, xhr) => {
                alert(JSON.stringify(obj_data));
                for(let each of obj_data){
                    $("#div_list_board").append("<a href = '/board/detail/" + each["order"] + "'>" + each["order"] + "//" + each["title"] + "<br/>" + "<a/>");
                }
            },
            error: (obj_data, status, error) => {
                alert("error!!");
                alert(JSON.stringify(obj_data));
            }

        })
    }

</script>
<script   src="https://code.jquery.com/jquery-3.7.1.js"   integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="   crossorigin="anonymous"></script>
</body>
</html>

결과 화면


[5] detail page에서 특정 한 데이터 불러오기

1) BoardRestController.java 내용 수정하기

    @GetMapping({"/detail"})
    public List<Map<String, Object>> detail(@RequestParam String order) {

        int index = Integer.parseInt(order) - 1;

        Map<String, Object> boardMap = boardList.get(index);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("resultCOde", 200);
        resultMap.put("detail_board", boardMap);

        return boardList;
    }

: /detail get 요청이 왔을 때 처리할 함수 (boardList의 index 값의 내용을 반환)

2) detail.html 코드 작성하기

<!DOCTYPE html>
<html>
<head>
    <title>타이틀</title>
</head>
<body>
detail page입니다.

<input type = "text" id = "detail_board_order"/>

<div id = "div_list_board">
</div>

<button onclick="detail_board()">글 전체 목록</button>
<script>

    function detail_board(){
        $.ajax({
            url : "/api/board/detail",
            type : "GET",
            contentType : 'application/json; charset=utf-8',
            data : { order : $("#detail_board_order").val()},
            cache : false,
            success : (obj_data, status, xhr) => {
                alert(JSON.stringify(obj_data));

            },
            error: (obj_data, status, error) => {
                alert("error!!");
                alert(JSON.stringify(obj_data));
            }

        })
    }

</script>
<script   src="https://code.jquery.com/jquery-3.7.1.js"   integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="   crossorigin="anonymous"></script>
</body>
</html>

결과 화면

: 1번째 값이 정상적으로 경고창에 잘 띄어지는 것을 볼 수 있다.

  • 다음에 해야 할 부분은 input에 index를 입력하는 것이 아닌, a 태그로 이동 시에 바로 보여질 수 있게 구현.

[번외] 다음에 해야 할 부분을 미리 해보면 아래와 같이 할 수 있다.

BoardController.java 파일 수정


: redirect를 사용하고, '?id'를 사용하여 URL Parameter를 사용하여 몇 번째 게시물인지 지정한다.

detail.html 파일 수정

: 페이지 로드 시 URL Parameter에 있는 값을 가져와서 input 태그 안의 value에 저장한다.

결과 화면

profile
안녕하세요, 사용자들의 문제 해결을 중심으로 하는 프론트엔드 개발자입니다. 티스토리로 전환했어요 : https://pangil-log.tistory.com

0개의 댓글