이전 세팅관련 포스팅에 이어 간단한 crud 게시판을 만들어보기위해 daointer, dao, controller, jsp를 살펴보도록 하자
package ABC.data;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ABCInter extends JpaRepository<ABCDto, Long> { }
package ABC.data;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository //리포지터리 등록
public class ABCDao {
@Autowired //오토와이어
ABCInter ABCInter;
//insert
public void insertABC(ABCDto dto) {
ABCInter.save(dto); //id타입 유무에 따라 자동으로 insert인지 update인지 구분
}
//전체출력
public List<ABCDto> getAllDatas(){
return ABCInter.findAll();
}
//num에 대한 dto반환
public ABCDto getData(Long num) {
return ABCInter.getById(num);
}
//수정
public void updateABC(ABCDto dto) {
ABCInter.save(dto); //num이 포함되어 있으므로 수정으로 인식함
}
//삭제
public void deleteABC(Long num) {
ABCInter.deleteById(num);
}
}
spring에서는 별도의 mapper로 sql을 작성해 삽입해야 했지만 boot는 자동으로 기능을 지원한다. insert와 update는 save, list는 findAll(), getData는 getById(num), delete는 deleteById(num)으로 넘긴다.
package ABC.data;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller //Controller 설정
public class ABCController {
@Autowired //오토와이어로 연결
ABCDao dao;
//list에서 addform으로 단순이동
@GetMapping("/ABCform")
public String form() {
return "ABC/addform";
}
//list에서 updateform으로 이동 get넘버로 넘어감
@GetMapping("/updateform")
public String form2(@RequestParam Long num,Model model) {
ABCDto dto=dao.getData(num);
model.addAttribute("dto", dto);
//dto를 받아야 수정창에서 원래 값 표시 가능
return "ABC/updateform";
}
//리스트 메서드, list.jsp에 출력
@GetMapping({"/","/list"}) //루트값 혹은 list에 맵핑
public ModelAndView list() {
ModelAndView mview=new ModelAndView();
List<ABCDto> list= dao.getAllDatas();
//리퀘스트 저장 받아오기
mview.addObject("list",list);
mview.addObject("count",list.size());
//주소 값
mview.setViewName("ABC/list");
return mview;
}
//인서트 메서드, addform의 저장과 연결
@PostMapping("/insert")
public String insert(@ModelAttribute ABCDto dto) {
dao.insertABC(dto);
return "redirect:list";
}
//업데이트 메서드, updateform.jsp의 수정 버튼과 연결
@PostMapping("/update")
public String update(@ModelAttribute ABCDto dto) {
dao.updateABC(dto);
return "redirect:list";
}
//삭제 메서드, list.jsp의 삭제 버튼과 연결
@GetMapping("/deleteform")
public String delete(@RequestParam Long num) {
dao.deleteABC(num);
return "redirect:list";
}
}
list에서 add, update form으로 가는 getmapping 메서드와 실제 crud를 실행하는 메서드 작성. controller는 spring과 흡사하다.
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script></head>
<body>
<form action="insert" method="post">
<table class="table table-bordered" style="width: 500px;">
<caption>ABC</caption>
<tr>
<th bgcolor="#grey">name</th>
<td>
<input type="text" name="name" class="form-control" style="width: 200px;" required="required">
</td>
</tr>
<tr>
<th bgcolor="#grey">price</th>
<td>
<input type="text" name="price" class="form-control" style="width: 200px;" required="required">
</td>
</tr>
<tr>
<th bgcolor="#grey">color</th>
<td>
<input type="color" name="color" class="form-control" style="width: 200px;" required="required">
</td>
</tr>
<tr>
<tr>
<th bgcolor="#grey">guip</th>
<td>
<input type="date" name="guip" class="form-control" style="width: 200px;" required="required">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="btn btn-info">입력</button>
<button type="button" onclick="location.href='list'" class="btn btn-danger">목록</button>
</td>
</tr>
</table>
</form>
</body>
</html>
POST방식으로 값을 submit한다. 이때 form의 action은 insert로 dao의 인서트 맵핑과 일치시킨다.
Update폼의 경우 아래 히든값을 폼아래 삽입시키고 각 입력창마다 value값을 기존값으로 할 수 있도록 설정한다.
<input type="hidden" name="num" value="${dto.num }">
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<img alt="" src="01.png">
<button type="button" class="btn btn-danger" style="margin-left: 200px;" onclick="location.href='ABCform'">입력button>
<h4 class="alert alert-success" style="width: 800px;">총 ${count }개 정보가 있습니다.</h4>
<table class="table table-bordered" style="width: 800px;">
<caption>ABC 정보</caption>
<tr>
<th width="60">번호</th>
<th width="130">이름</th>
<th width="80">색상</th>
<th width="150">가격</th>
<th width="180">구입일</th>
<th width="180">등록일</th>
<th width="120">편집</th>
</tr>
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td>${i.count }</td>
<td>${dto.ABCname }</td>
<td>
<div style="background-color: ${dto.ABCcolor}" class="box"></div>
</td>
<td><fmt:formatNumber value="${dto.ABCprice }" type="currency"/></td>
<td>
${dto.ABCguip }
</td>
<td>
<fmt:formatDate value="${dto.guipday }" pattern="yyyy-MM-dd HH:mm시"/>
</td>
<td>
<button type="button" class="btn btn-default" onclick="location.href='updateform?num=${dto.num}'">수정</button>
<button type="button" class="btn btn-default" onclick="location.href='deleteform?num=${dto.num}'">삭제</button>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
역시 Spring과 다를바 없다. jstl을 이용해 값을 출력한다.