JSP - 07

월요일좋아·2022년 11월 3일
0

JSP

목록 보기
7/9
post-custom-banner

게시판 글 읽기, 삭제, 수정

기본

boardList.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%@ include file="dbconn.jsp"%>

<header class="container mt-3">
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-4">
      <h1 class="text-center">게시물 리스트 페이지</h1>
    </div>
  </div>
</header>
<main class="container mt-4">
  <div class="row">
    <div class="col-sm">
      <table class="table table-hover table-striped">
        <thead>
          <tr>
            <th>글번호</th>
            <th>글제목</th>
            <th>글쓴이</th>
            <th>등록시간</th>
            <th>조회수</th>
          </tr>
        </thead>
        <tbody>
        <%
          PreparedStatement pstmt = null;
          ResultSet rs = null;

          try {
//    전체 글 조회 쿼리문
            String sql = "SELECT seq, title, user_id, create_date, cnt FROM board WHERE deleted_yn = 'N'  order by seq DESC ";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
              int seq = rs.getInt("seq");
              String title = rs.getString("title");
              String userId = rs.getString("user_id");
              String createDt = rs.getString("create_date");
              int cnt = rs.getInt("cnt");
        %>
          <tr>
            <td><%=seq%>></td>
<%--            게시물 제목 누르면 그 게시물 내용이 있는 페이지로 이동되도록, ? 는 변수 들어가는 위치--%>
<%--              여기서 seq = 내가 선택한 글 번호 --%>
            <td><a href="boardDetail.jsp?seq=<%=seq%>"><%=title%></a></td>
            <td><%=userId%></td>
            <td><%=createDt%></td>
            <td><%=cnt%></td>
          </tr>
        <%
            }
          }
          catch (SQLException e) {
            out.println("SQLException : " + e.getMessage());
          }
          finally {
            if (rs != null) {
              rs.close();
            }
            if (pstmt != null) {
              pstmt.close();
            }
            if (conn != null) {
              conn.close();
            }
            }
        %>
        </tbody>
      </table>
      <div class="d-flex justify-content-end">
        <a href="boardWrite.jsp" class="btn btn-primary">글쓰기</a>
      </div>
    </div>
  </div>
</main>
<footer class="container-fluid mt-5 p-5 border-top">
  <p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>
</html>

글 읽기

boardDitail.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
    <title>상세 글 읽기</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        window.addEventListener('DOMContentLoaded', function () {
            const btnList = document.querySelector("#btn-list");
            btnList.addEventListener('click', function () {
                history.back();
            })
        });
    </script>
</head>
<body>
<%--<h1>글읽기 페이지</h1>--%>
<%@include file="dbconn.jsp"%>

<header class="container mt-3">
    <div class="p-5 mb-4 bg-light rounded-3">
        <div class="container-fluid py-4">
            <h1 class="text-center">게시물 상세 글읽기 페이지</h1>
        </div>
    </div>
</header>

<%
// seq를 숫자로 받아줘야함 : 게시판 목록 페이지에서 넘겨받은 글 번호
    int seq = Integer.parseInt(request.getParameter("seq"));

    String title = "";
    String contents = "";
    String userId = "";
    String createDate = "";
    String updateDate = "";
    int cnt = 0;

//    DB 연결
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        String sql = "SELECT seq, title, contents, user_id, create_date, update_date, cnt FROM board ";
        sql += "WHERE seq = ?";
        pstmt = conn.prepareStatement(sql);
//        seq를 숫자로 넣어줘야하니까 setInt
        pstmt.setInt(1, seq);
//        select문 동작시키기 위해
        rs = pstmt.executeQuery();

        if (rs.next()) { // 데이터 들어있는지 확인
            title = rs.getString("title"); // 데이터가 있으면 해당 코드 실행
            contents = rs.getString("contents");
            userId = rs.getString("user_Id");
            createDate = rs.getString("create_date");
            updateDate = rs.getString("update_date");
            cnt = rs.getInt("cnt");

           // out.print(title + "<br>");
           // out.print(contents + "<br>");
           // out.print(userId + "<br>");
           // out.print(createDate + "<br>");
           // out.print(updateDate + "<br>");
           // out.print(cnt + "<br>");
        }
    }
    catch (SQLException e) {
        out.print(e.getMessage());
    }
    finally {
        if (rs != null) {
            rs.close();
        }
        if (pstmt != null) {
            pstmt.close();
        }
        if (conn != null) {
            conn.close();
        }

    }
%>
<main class="container mt-5">
    <div class="row">
        <form action="boardUpdate_process.jsp" method="post">
        <div class="col-sm-6 mx-auto">
                <div class="form-floating my-3">
<%--                    임의로 수정하면 안 되는 부분 : readonry 또는 disabled 추가해주면 됨 --%>
                    <input type="text" class="form-control" id="seq" name="seq" placeholder="글번호를 입력하세요" readonly value="<%=seq%>">
                    <label for="seq" class="form-label">Seq</label>
                </div>
                <div class="form-floating my-3">
                    <input type="text" class="form-control" id="title" name="title" placeholder="제목을 입력하세요" value="<%=title%>">
                    <label for="title" class="form-label">Title</label>
                </div>
                <div class="form-floating my-3">
                    <input type="text" class="form-control" id="user-id" name="userId" placeholder="ID를 입력하세요" disabled value="<%=userId%>">
                    <label for="user-id" class="form-label">ID</label>
                </div>
                <div class="form-floating my-3">
                    <input type="text" class="form-control" id="create-date" name="createDate" placeholder="날짜를 입력하세요" readonly value="<%=createDate%>">
                    <label for="create-date" class="form-label">Date</label>
                </div>
                <div class="form-floating my-3">
                    <input type="text" class="form-control" id="board-cnt" name="boardCnt" placeholder="조회수를 입력하세요" readonly value="<%=cnt%>">
                    <label for="board-cnt" class="form-label">Count</label>
                </div>
                <div class="form-floating my-3">
                    <textarea class="form-control" id="contents" name="contents" placeholder="내용을 입력하세요"><%=contents%></textarea>
                    <label for="contents" class="form-label">Contents...</label>
                </div>
                <div class="my-3 row">
                    <div class="col-sm">
                        <button class="btn btn-secondary" type="button" id="btn-list">목록으로</button>
                    </div>
                    <%--                        me = margin end --%>
                    <div class="col-sm d-flex justify-content-end">
                            <button class="btn btn-warning me-2" type="submit">수정</button>
                        </form>
                        <form action="boardDelete_prosess.jsp" method="post">
                            <input type="hidden" name="seq" value="<%=seq%>">
                            <button class="btn btn-danger" type="submit">삭제</button>
                        </form>
                    </div>
                </div>
        </div>
    </div>
</main>

<footer class="container-fluid mt-5 p-5 border-top">
    <p class="lead text-muted text-center">made by bitc java505</p>
</footer>
</body>


</html>

삭제 기능

boardDelete_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<%-- UI 없는 process 기능용 페이지이기 떄문에 불필요한 코드 다 삭제 --%>

<%@include file="dbconn.jsp"%>
<%
  int seq = Integer.parseInt(request.getParameter("seq"));

  String sql = "UPDATE board SET deleted_yn = 'Y' ";
  sql += "WHERE seq = ?";

  PreparedStatement pstmt = null;

  try {
    pstmt = conn.prepareStatement(sql);
    pstmt.setInt(1, seq);
    pstmt.executeUpdate(); // 데이터 보내기
  }
  catch (SQLException e) {
    out.println(e.getMessage());
  }
  finally {
    if (pstmt != null) {
      pstmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }

//  다 끝나면 원래 페이지로 돌아가야함
  response.sendRedirect("boardList.jsp");
%>

수정 기능

boardUpdate_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>

<%@include file="dbconn.jsp"%>
<%-- 폼만을 이용하는 방식 --%>
<%
  request.setCharacterEncoding("UTF-8");

  int seq = Integer.parseInt(request.getParameter("seq"));
  String title = request.getParameter("title");
  String contents = request.getParameter("contents");

  String sql = "UPDATE board SET title = ?, contents = ?";
  sql += "WHERE seq = ? ";

  PreparedStatement pstmt = null;


  try {
    pstmt = conn.prepareStatement(sql);
    pstmt.setString(1, title);
    pstmt.setString(2, contents);
    pstmt.setInt(3, seq);
    pstmt.executeUpdate(); // 데이터 보내기
  }
  catch (SQLException e) {
    out.println(e.getMessage());
  }
  finally {
    if (pstmt != null) {
      pstmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }

  response.sendRedirect("boardList.jsp");
%>

조회수 count

boardDetail.jsp의 try 문 안에 아래 코드 추가

 // 조회수 카운트 기능
        String sql = "UPDATE board SET cnt = cnt + 1 WHERE seq = ? ";
        pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, seq);
        pstmt.executeUpdate(); // 현재 sql문데이터 한번 날려주고

Json이란?

javascript object notation의 줄임말로 자바스크림트 객체 문법을 사용하는 문자 기반의 전송 포맷

- Javascript -

  • parse() : JSON 타입 형태의 문자열을 JSON 객체로 변환
    "{key1: 'asdf'}" -> {key: 'asdf'}
    String 타입을 진짜 Object타입으로 변환

  • stringify() : JSON 객체를 JSON 타입의 문자열로 변환
    {key1: 'asdf'} -> "{key: 'asdf'}"

- Java -

  • Gson : java에서 json 객체를 사용하기 위해 google에서 개발한 java 라이브러리

  • 라이브러리 추가(gradle) : implementation 'com.google.code.gson:gson:2.10' 추가

- 사용법 -

  • Gson 객체 생성 :
    Gson gson = new Gson();

  • Json 객체 생성 :
    JsonObject jsonObject = new JsonObject();

  • Json 객체에 JSon 데이터 추가하기(key, value) :
    jsonObject.addProperty("이름", "데이터");

  • Json 객체를 Json 문자열로 변환 :
    String str = gson.toJson(jsonObject);

  • Java Object를 Json 으로 변환 :

class Student {
    int id;
    String name;

    public Student(id, name) {
    this.id = id;
    this.name = name
    }
}
Student stu = new Student(1001, "홍길동");
Gson gson = new Gson();
String str = gson.toJson(stu);
  • Json 을 Java Object로 변환 :
String str = "{\"id\": 1001, \"name\": \"홍길동\"}";
Gson gson = new Gson();
Student stu = gson.fromJson(str, Student.Class);
  • HashMap을 Json으로 변환 :
Map<String, String> map = new HashMap<>();
map.put("id", "1001");
map.put("name", "홍길동");
   
Gson gson = new Gson();
String str = gson.toJson(map);
   
JsonHashMap으로 변환 :
String str = "{\"id\": \"1001\", \"name\": \"홍길동\"}";
Gson gson = new Gson();
   
Map<String, String> map = gson.fromJson(str, Map.class);

자바스크립트에서 하는 방법 : boardList의 a코드 연결 boardDetail2.jsp로 수정

boardDetail2.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2022-11-02
  Time: 오전 9:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html>
<%--2번 방식을 사용하면 읽기, 수정, 삭제 다 넣을 수 있다.--%>
<html>
<head>
  <title>상세 글 읽기</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    window.addEventListener('DOMContentLoaded', function () {
      const btnList = document.querySelector('#btn-list');
      const btnUpdate = document.querySelector('#btn-update');
      const btnDelete = document.querySelector('#btn-delete');
      const frm = document.querySelector('#frm');

      btnList.addEventListener('click', function () {
        history.back();
      });

      btnUpdate.addEventListener('click', function (){
        frm.action = "boardUpdate_process.jsp";
        frm.submit();
      });

      btnDelete.addEventListener('click', function (){
        frm.action = "boardDelete_process.jsp";
        //이동할 위치
        frm.submit();
        //    submit버튼과 동일한 효과
      });
    });
  </script>
</head>
<body>
<%--<h1>글읽기 페이지</h1>--%>
<%@ include file="dbconn.jsp" %>
<%
  int seq = Integer.parseInt(request.getParameter("seq"));

  String title = "";
  String contents = "";
  String userId = "";
  String createDate = "";
  String updateDate = "";
  int boardCnt = 0;
%>

<%
  PreparedStatement pstmt = null;
  ResultSet rs = null;


  try {
//        카운트 수 늘리기
    String sql = "UPDATE board SET cnt = cnt+1 where seq = ? ";
    pstmt = conn.prepareStatement(sql);
    pstmt.setInt(1, seq);
    pstmt.executeUpdate();

//        값 가져오기
    sql = "SELECT seq, title, contents, user_id, create_date, update_date, cnt FROM board ";
    sql += "WHERE seq = ? ";
    pstmt = conn.prepareStatement(sql);
    pstmt.setInt(1, seq);
    rs = pstmt.executeQuery();


    if (rs.next()) {
      title = rs.getString("title");
      contents = rs.getString("contents");
      userId = rs.getString("user_id");
      createDate = rs.getString("create_date");
      updateDate = rs.getString("update_date");
      int cnt = rs.getInt("cnt");

//    out.print(title + "<br>");
//    out.print(contents + "<br>");
//    out.print(userId + "<br>");
//    out.print(createDate + "<br>");
//    out.print(updateDate + "<br>");
//    out.print(cnt);

    }
  } catch (SQLException e) {
    out.println(e.getMessage());
  } finally {
    if (rs != null) {
      rs.close();
    }
    if (pstmt != null) {
      pstmt.close();
    }
    if (conn != null) {
      conn.close();
    }
  }
%>

<header class="container mt-3">
  <div class="p-5 mb-4 bg-light rounded-3">
    <div class="container-fluid py-4">
      <h1 class="text-center">상세 글 읽기 페이지</h1>
    </div>
  </div>
</header>

<main class="container mt-5">
  <div class="row">
    <form action="#" method="post" id="frm">
      <div class="col-sm-6 mx-auto">
        <%--      <form action="boardWrite_process.jsp" method="post" class="border rounded-3 p-4">--%>

        <div class="form-floating my-3">
          <input type="text" class="form-control" id="seq" name="seq" placeholder="글 번호를 입력하세요" readonly
                 value="<%=seq%>">
          <label for="seq" class="form-label">Seq</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="title" name="title" placeholder="제목을 입력하세요"
                 value="<%=title%>">
          <label for="title" class="form-label">Title</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="user-id" name="userId" placeholder="ID를 입력하세요" disabled
                 value="<%=userId%>">
          <%--          disable과 readonly는 둘 다 수정 불가하지만 disable은 바탕색 바뀜--%>
          <label for="user-id" class="form-label">ID</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" input class="form-control" id="create-date" name="createDate" rows="10"
                 placeholder="날짜를 입력하세요" readonly
                 value="<%=createDate%>">
          <label for="create-date" class="form-label">Date</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="board-cnt" name="boardCnt" rows="10"
                 placeholder="조회수를 입력하세요" readonly
                 value="<%=boardCnt%>">
          <label for="board-cnt" class="form-label">Count</label>
        </div>
        <div class="form-floating my-3">
          <input type="text" class="form-control" id="contents" name="contents" rows="10"
                 placeholder="내용을 입력하세요"
                 value="<%=contents%>">
          <label for="contents" class="contents">Contents...</label>
        </div>

        <div class="my-3 row">
          <div class="col-sm">
            <button class="btn btn-secondary" type="button" id="btn-list">목록으로</button>
          </div>
          <div class="col-sm d-flex justify-content-end">
            <button class="btn btn-warning me-2" type="button" id="btn-update">수정</button>
            <button class="btn btn-danger" type="button" id="btn-delete">삭제</button>
          </div>
        </div>
      </div>
    </form>
  </div>
</main>


</body>

</html>

에이젝스에서 하는 방법 (+gson 이용)

cal.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Title</title>

    <!--    제이쿼리 추가 : https://developers.google.com/speed/libraries#jquery-->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#btn-ok').on('click', function () {
                const number3 = $('#num3').val();
                const number4 = $('#num4').val();

                //    ajax문법 시작
                $.ajax({
                    // url: ajax를 통해서 접속하고자 하는 서버 주소를 입력
                    url: 'cal_process.jsp',
                    // type: 통신 방식을 설정
                    type: 'post',
                    // form으로 실행했을때 들어가는 name: data, 매개변수로 들어갈 data 없으면 생략가능
                    data: {num1: number3, num2: number4},
                    // success: 통신이 정상적으로 이루어질 경우 실행
                    success: function() {
                        alert("통신 성공");
                    },
                    // error: 통신 시 오류가 발생할 경우 실행
                    error: function() {
                        alert("ajax 통신 시 오류가 발생했습니다.");
                    }
                });
            });


            $('#btn-ok2').on('click', function () {
                const datas = {num1: $('#num5').val(), num2: $('#num6').val()};

                $.ajax({
                   url: "cal_process2.jsp",
                   type: "post",
                   data: datas,
                   // dataType: 자바스크립트로 넘기는 데이터의 종류 선택가능(생략하면 자동으로 됨, 데이터타입오류나면 직접선언해주면됨)
                   success: function (data) {
                        obj = JSON.parse(data);

                        if (obj.result == "success") {
                            alert("통신성공!!\n전송된 데이터 : " + obj.value);
                        }
                        else {
                            alert("전송된 데이터가 없습니다.");
                        }
                   },
                   error: function () {
                       alert('통신 중 오류가 발생했습니다.');
                   }
                });
            });
        });
    </script>
</head>
<body>
<div class="container mt-5">
    <div class="row">
        <div class="col-sm-6">
            <form action="cal_process.jsp" method="post">
                <label for="num1" class="form-label">숫자 1 : </label>
                <input type="text" class="form-control" id="num1" name="num1" placeholder="숫자를 입력해주세요">
                <label for="num2" class="form-label">숫자 2 : </label>
                <input type="text" class="form-control" id="num2" name="num2" placeholder="숫자를 입력해주세요">
                <div class="my-3">
                    <button type="submit" class="btn btn-success">form으로 계산</button>
                </div>
            </form>
        </div>
    </div>
    <br><br><br>
    <div class="row">
        <div class="col-sm-6">
            <label for="num3" class="form-label">숫자 1 : </label>
            <input type="text" class="form-control" id="num3" name="num1" placeholder="숫자를 입력해주세요">
            <label for="num4" class="form-label">숫자 2 : </label>
            <input type="text" class="form-control" id="num4" name="num2" placeholder="숫자를 입력해주세요">
            <div class="my-3">
                <button type="button" class="btn btn-primary" id="btn-ok">ajax로 계산</button>
            </div>
        </div>
    </div>
    <br><br><br>
<!--    JSON 방식 -->
    <div class="row">
        <div class="col-sm-6">
            <label for="num5" class="form-label">숫자 1 : </label>
            <input type="text" class="form-control" id="num5" placeholder="숫자를 입력해주세요">
            <label for="num6" class="form-label">숫자 2 : </label>
            <input type="text" class="form-control" id="num6" placeholder="숫자를 입력해주세요">
            <div class="my-3">
                <button type="button" class="btn btn-info" id="btn-ok2">ajax로 계산 후 응답</button>
            </div>
        </div>
    </div>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>
-->

car_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>

    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>

</head>
<body>
<%
    request.setCharacterEncoding("utf-8");
    int num1 = Integer.parseInt(request.getParameter("num1"));
    int num2 = Integer.parseInt(request.getParameter("num2"));

    out.println("두 수의 덧셈은 : " + (num1 + num2));
    System.out.println("두 수의 덧셈은 : " + (num1 + num2));
%>
</body>
</html>

car_process2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="com.google.gson.JsonObject" %>

<%
  int num1 = Integer.parseInt(request.getParameter("num1"));
  int num2 = Integer.parseInt(request.getParameter("num2"));

  Gson gson = new Gson();
  JsonObject obj = new JsonObject();

  obj.addProperty("result", "success");
  obj.addProperty("value", num1 + num2);

  out.print(gson.toJson(obj));
%>

Json 연습

Student.clsss

package com.bitc.jspchap13;

public class Student {
    private int id;
    private String name;

    public Student(int id, String name) {
        this.id = id;
        this.name = name;

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

jsonTest.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.util.*" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="com.google.gson.JsonObject" %>
<%@ page import="com.sun.tools.javac.jvm.Gen" %>
<%@ page import="com.bitc.jspchap13.Student" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  Gson gson = new Gson();
  Student stu = new Student(1001, "홍길동");

  String jsonStr = gson.toJson(stu);

  out.print(jsonStr);
  %>

  <br><br><br>
<%
  JsonObject jobj = new JsonObject();
  jobj.addProperty("id", 1002);
  jobj.addProperty("name", "아이유");

  out.print(jobj);
%>
<br><br><br>
<%
    jsonStr = "{\"id\": 1003, \"name\": \"유재석\"}";

    Student stu1 = gson.fromJson(jsonStr, Student.class);
    out.print(stu1); // 결과: com.bitc.jspchap13.Student@368e3ee4

    out.print(stu1.getId());
    out.print(stu1.getName());


%>
</body>
</html>
post-custom-banner

0개의 댓글