✔ EmpController.java
package edu.example.ex.controller; 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.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import edu.example.ex.page.Criteria; import edu.example.ex.page.PageVO; import edu.example.ex.service.EmpService; import edu.example.ex.vo.BoardVO; import edu.example.ex.vo.EmpVO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j // 로그 @Controller @RequestMapping("/emp/*") @RequiredArgsConstructor public class EmpController { @Autowired private final EmpService empService; @GetMapping("/empList") public String empList(EmpVO empVO, Model model) { log.info("empList() .."); model.addAttribute("emps", empService.getList()); return "/emp/empList"; } @GetMapping("/contentView") public String contentView(EmpVO empVO, Model model) { log.info("content_view() .."); int empno = empVO.getEmpno(); empVO = empService.get(empno); model.addAttribute("contentView", empVO); return "/emp/contentView"; } @PostMapping("/modify") public String modify(EmpVO empVO, Model model) { log.info("modify() .."); int rn = empService.modify(empVO); log.info("modify() .. result number::" + rn); return "redirect:empList"; } @GetMapping("/delete") public String delete(EmpVO empVO, Model model) { log.info("delete() .."); int rn = empService.delete(empVO); return "redirect:empList"; } @GetMapping("/write_view") public String write_view() { return "/emp/write_view"; } @PostMapping("/write") public String write(EmpVO empVO) { log.info("write() .."); int rn = empService.write(empVO); return "redirect:list"; } @GetMapping("/reply_view") public String reply_view(EmpVO empVO, Model model) { log.info("reply_view().."); model.addAttribute("reply_view", empService.get(empVO.getEmpno())); return "/emp/reply_view"; } @GetMapping("/reply") public String reply(EmpVO empVO) { log.info("reply() .."); empService.registerReply(empVO); return "redirect:list"; // 로직 수행 후 list로 redirect 함 } // http://localhost:8282/list2 // list2?pageNum=5&amount=10">1</a> @GetMapping("/empList2") public String empList2(Criteria cri, Model model) { // command 객체 먼저 실행 -> Criteria.java의 Criteria() 메소드 실행하여 처음에는 // 1,10을 메모리에 저장했다가 주소창에서 pageNum 설정에 따라 setter함수가 적용되어 페이지 변경 log.info("list2() .."); log.info("list2() Criteria " + cri); // 게시판 10개씩 가지고 오는 부분 model.addAttribute("emps", empService.getList(cri)); // 페이징을 위한 처리 int total = empService.getTotal(); log.info("total" + total); model.addAttribute("pageMaker", new PageVO(cri, total)); return "/emp/empList2"; } @GetMapping("/dept1") public String dept1() { log.info("dept1() .."); System.out.println(empService.getEmpDeptOneVOList()); return "/emp/empList2"; } @GetMapping("/dept2") public String dept2(Model model) { log.info("dept2() .."); System.out.println(empService.getEmpDeptList()); model.addAttribute("empDeptList",empService.getEmpDeptList()); return "/emp/empDept"; } }
✔ DeptMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="edu.example.ex.mapper.DeptMapper"> <select id="getEmpDeptOneVOList" resultType="EmpDeptVO"> <![CDATA[ select * from emp,dept where emp.deptno = dept.deptno ]]> </select> <resultMap id="empMap" type="EmpVO"> <id property="empno" column="empno" /> <!-- key에는 관습적으로 id를 달아준다 --> <result property="ename" column="ename" /> <result property="job" column="job" /> <result property="mgr" column="mgr" /> <result property="hiredate" column="hiredate" /> <result property="sal" column="sal" /> <result property="comm" column="comm" /> <result property="deptno" column="deptno" /> </resultMap> <resultMap id="deptMap" type="DeptVO"> <id property="deptno" column="deptno" /> <!-- property="setDeptno()" Set함수를 불러오는 것 --> <result property="dname" column="dname" /> <result property="loc" column="loc" /> <collection property="empList" resultMap="empMap" /> <!-- collection은 1:n일 때 사용하고 1:1일 때는 association태그를 사용 --> </resultMap> <select id="getEmpDeptList" resultMap="deptMap"> <![CDATA[ select * from emp,dept where emp.deptno = dept.deptno ]]> </select> </mapper>
✔ DeptMapper.java
package edu.example.ex.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import edu.example.ex.vo.DeptVO; import edu.example.ex.vo.EmpDeptVO; @Mapper public interface DeptMapper { public List<EmpDeptVO> getEmpDeptOneVOList(); public List<DeptVO> getEmpDeptList(); }
✔ EmpService.java
package edu.example.ex.service; import java.util.List; import edu.example.ex.page.Criteria; import edu.example.ex.vo.BoardVO; import edu.example.ex.vo.DeptVO; import edu.example.ex.vo.EmpDeptVO; import edu.example.ex.vo.EmpVO; public interface EmpService { public abstract List<EmpVO> getList(); public EmpVO get(int empno); int modify(EmpVO emp); // 글 수정 int delete(EmpVO emp); // 글 삭제 int write(EmpVO emp); // 글 등록 void registerReply(EmpVO emp); // 댓글 등록 int getTotal(); public List<EmpVO> getList(Criteria criteria); public List<EmpDeptVO> getEmpDeptOneVOList(); public List<DeptVO> getEmpDeptList(); }
✔ EmpServiceImpl.java
package edu.example.ex.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import edu.example.ex.mapper.DeptMapper; import edu.example.ex.mapper.EmpMapper; import edu.example.ex.page.Criteria; import edu.example.ex.vo.BoardVO; import edu.example.ex.vo.DeptVO; import edu.example.ex.vo.EmpDeptVO; import edu.example.ex.vo.EmpVO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @Service @RequiredArgsConstructor // +@Autowired 하면 생성자 주입 (없으면 필드 주입) public class EmpServiceImpl implements EmpService { @Autowired private final EmpMapper mapper; @Autowired private final DeptMapper deptMapper; @Override public List<EmpVO> getList() { log.info("getList() .."); return mapper.getList(); } @Override public EmpVO get(int empno) { log.info("get(int empno) .."); return mapper.read(empno); } @Override public int modify(EmpVO emp) { log.info("modify() .."); return mapper.update(emp); } @Override public int delete(EmpVO emp) { log.info("delete() .."); return mapper.remove(emp); } @Override public int write(EmpVO emp) { log.info("write() .."); return mapper.insert(emp); } @Transactional @Override public void registerReply(EmpVO emp) { log.info("registerReply() .."); mapper.updateShape(emp); mapper.insertReply(emp); } @Override public int getTotal() { log.info("getTotal() .."); return mapper.getTotalCount(); } @Override public List<EmpVO> getList(Criteria criteria) { log.info("getList(Criteria criteria) .."); return mapper.getListWithPaging(criteria); } @Override public List<EmpDeptVO> getEmpDeptOneVOList() { return deptMapper.getEmpDeptOneVOList(); } @Override public List<DeptVO> getEmpDeptList() { return deptMapper.getEmpDeptList(); } }
✔ empDept.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <table width="600" cellpadding="0" cellspacing="0" border="1"> <tr> <th>사원번호</th> <th>사원이름</th> <th>부서</th> <th>위치</th> </tr> <c:forEach var="deptlist" items="${empDeptList}"> <!-- 이중for문 사용 --> <c:forEach var="emplist" items="${deptlist.empList}"> <tr> <td>${emplist.empno}</td> <td>${emplist.ename}</td> <td>${deptlist.dname}</td> <td>${deptlist.loc}</td> </tr> </c:forEach> </c:forEach> </table> </body> </html>
- 결과
기능 | 메소드 | Rest URI | 기존 URI |
---|---|---|---|
게시판 전체 조회 | GET | /board | /list |
게시판 컨텐츠 조회(1개조회) | GET | /board/{bid} | /content_view |
게시판 글 생성 | POST | /board | /write |
게시판 글 수정 | PUT | /board/{bid} | /moderfiy?bid=100 |
게시판 삭제 | DELETE | /board/{bid} |
✔ RestBoardController.java
package edu.example.ex.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.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import edu.example.ex.page.Criteria; import edu.example.ex.page.PageVO; import edu.example.ex.service.BoardService; import edu.example.ex.vo.BoardVO; import lombok.extern.slf4j.Slf4j; @Slf4j // 로그 @RequestMapping("/rboard/*") @RestController // restful 전용 컨트롤러 public class RestBoardController { @Autowired private BoardService boardService; @GetMapping("/") public String rboard() { return "<h1>이제는 restful</h1>"; } @GetMapping("/list") public List<BoardVO> list() { log.info("list() .."); return boardService.getList(); } // rboard/bid @DeleteMapping("/{bid}") public int rest_delete(BoardVO boardVO) { log.info("rest_delete() .."); return boardService.delete(boardVO); } }
✔ rest_list.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> /* $.ajax({ url : '서비스 주소' , data : '서비스 처리에 필요한 인자값' , type : 'HTTP방식' (POST/GET 등) , dataType : 'return 받을 데이터 타입' (json, text 등) , success : function('결과값'){ // 서비스 성공 시 처리 할 내용 }, error : function('결과값'){ // 서비스 실패 시 처리 할 내용 } }); */ $(document).ready(function() { $.ajax({ type : "GET", url : "/rboard/list/", success : function(result) { console.log(result); var htmls=""; $("#list-table").html(""); $("<tr>" , { html : "<td>" + "번호" + "</td>"+ // 컬럼명들 "<td>" + "이름" + "</td>"+ "<td>" + "제목" + "</td>"+ "<td>" + "날짜" + "</td>"+ "<td>" + "히트" + "</td>" }).appendTo("#list-table") // 이것을 테이블에 붙임 if(result.length < 1){ htmls.push("등록된 댓글이 없습니다."); } else { $(result).each(function(){ htmls += '<tr>'; htmls += '<td>'+ this.bid + '</td>'; htmls += '<td>'+ this.bname + '</td>'; htmls += '<td>' for(var i=0; i < this.bindent; i++) { //for 문은 시작하는 숫자와 종료되는 숫자를 적고 증가되는 값을 적어요. i++ 은 1씩 증가 i+2 는 2씩 증가^^ htmls += '-' } htmls += '<a href="/rest_content_view.html?bid=' + this.bid + '">' + this.btitle + '</a></td>'; htmls += '<td>'+ this.bdate + '</td>'; htmls += '<td>'+ this.bhit + '</td>'; htmls += '<td>'+ '<input id=' + this.bid + " type='button' class='btn_delete' value='삭제'>" + '</td>'; htmls += '</tr>'; }); //each end htmls+='<tr>'; htmls+='<td colspan="5"> <a href="/write_view">글작성</a> </td>'; htmls+='</tr>'; } $("#list-table").append(htmls); }, error : function(e) { console.log(e); } }); }); </script> <script type="text/javascript"> $(document).ready(function (){ $(document).on("click","#list-table .btn_delete",function(){ console.log($(this).attr("id")); var id = $(this).attr("id"); $(this).parent().parent().remove(); $.ajax({ type : "DELETE", url : "/rboard/" + id, success: function (result) { console.log("삭제된 수: " + result); }, error: function (e) { console.log(e); } }); }); }); </script> </head> <body> <table id="list-table" width="500" cellpadding="0" cellspacing="0" border="1"> </table> </body> </html>
- 결과