기본적으로 jsp -> controller -> dao -> sql 순으로 작업이 진행된다.
개발자의 경우에는 sql -> dao -> controller -> jsp 순서로 작업하면 된다.
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
2. root-context.xml 에 아래 내용 추가하기. (DB와 연동)
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/데이터베이스이름?serverTimezone=Asia/Seoul"></property>
<property name="username" value="데이터베이스아이디"></property>
<property name="password" value="데이터베이스비밀번호"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<?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">
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/res/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="spring.mysql.*" />
</beans:beans>
package spring.mysql.mycar;
public class MyCarDto {
private String num;
private String carname;
private int carprice;
private String carcolor;
private String carguip;
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getCarname() {
return carname;
}
public void setCarname(String carname) {
this.carname = carname;
}
public int getCarprice() {
return carprice;
}
public void setCarprice(int carprice) {
this.carprice = carprice;
}
public String getCarcolor() {
return carcolor;
}
public void setCarcolor(String carcolor) {
this.carcolor = carcolor;
}
public String getCarguip() {
return carguip;
}
public void setCarguip(String carguip) {
this.carguip = carguip;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="mdto" type="spring.mysql.mycar.MyCarDto"/>
<typeAlias alias="cardto" type="spring.mysql.carmember.CarMemberDto"/>
</typeAliases>
</configuration>
<?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="spring.mysql.mycar.MyCarDao"> <!-- namespace의 경우 겹쳐질까봐 이렇게 세세하게 쓰는거다. Dao로 써야 하는건 아니다. -->
<!-- <mapper namespace="mymycar"> --> <!-- 별명과 같은 거라서 'mycar' 처럼 간단하게 써도 된다. -->
<!-- 전체 리스트 -->
<select id="getAllListOfMyCar" resultType="mdto"> <!-- resultType : 반환타입 -->
<!-- resultType(return값이라고 생각하자) 작성 시 packge까지 써야 합니다. 이걸 간단하게 하기 위해 mybatis에서 alias를 설정해준다. -->
select * from mycar order by num desc <!-- 여기서는 세미콜론 적으면 안된다. -->
</select>
<!-- 전체 개수 얻기 -->
<select id="getTotalCountOfMyCar" resultType="int">
select count(*) from mycar
</select>
<!-- insert -->
<insert id="insertOfMyCar" parameterType="mdto">
insert into mycar (carname,carprice,carcolor,carguip) values(#{carname},#{carprice},#{carcolor},#{carguip})
<!-- # : mybatis ,$ : ibatis, -->
</insert>
<delete id="deleteOfMyCar" parameterType="String">
delete from mycar where num=#{num}
</delete>
<!-- update 2단계 -->
<!-- 1. 수정폼 나타내기 -->
<select id="selectOneOfMyCar" resultType="mdto" parameterType="String">
select * from mycar where num=#{num}
</select>
<!-- 2. 수정하기 -->
<update id="updateOfMyCar" parameterType="mdto">
update mycar set carname=#{carname},carprice=#{carprice},carcolor=#{carcolor},carguip=#{carguip} where num=#{num}
</update>
</mapper>
package spring.mysql.mycar;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository // bean에 등록하는것.
public class MyCarDao {
// root-context 에서 받는다.
@Autowired
private SqlSession session; // SqlSession 이라는 Interface가 있고 그걸 가져와서 사용한다고 생각하면 된다. 해당 사항들은 root-context에
String namespace="spring.mysql.mycar.MyCarDao";
public int getTotalCount() {
return session.selectOne(namespace+".getTotalCountOfMyCar");
// return session.selectOne("getTotalCountOfMyCar");
// return session.selectOne("mymycar.getTotalCountOfMyCar"); // 괄호안에는 mapper에서 지정한 id값이 들어간다.
// 겹칠꺼 같으면 앞에 mapper의 "namespace값."을 앞에 써도 상관없다.
}
// insert
public void insertCar(MyCarDto dto) {
session.insert("insertOfMyCar", dto);
}
// 전체 목록 출력
public List<MyCarDto> getAllCars(){
return session.selectList("getAllListOfMyCar");
}
// delete
public void deleteCar(String num) {
session.delete("deleteOfMyCar", num);
}
// update를 위해 항목 찾기
public MyCarDto getData(String num) {
return session.selectOne("selectOneOfMyCar", num);
}
// update 하기
public void updateCar(MyCarDto dto) {
session.update("updateOfMyCar", dto);
}
}
package spring.mysql.mycar;
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
public class CarController {
@Autowired
MyCarDao dao;
@GetMapping("/kakao/list")
public String list(Model model) {
// dao로 부터 총 개수 가지고 오기
int totalCount=dao.getTotalCount();
// 목록 가져오기
List<MyCarDto> list=dao.getAllCars();
//request에 저장하는것.
model.addAttribute("totalCount", totalCount);
// request에 목록 가지고온거 저장하기
model.addAttribute("list", list);
return "car/carList";
}
@GetMapping("/kakao/writeForm")
public String carform() {
return "car/writeForm";
}
// insert
@PostMapping("/kakao/write")
public String insert(@ModelAttribute MyCarDto dto) {
dao.insertCar(dto);
return "redirect:list"; // redirect 의 경우 주소값을 주는것이다. 그래서 앞에 경로 상관없이 지점만 적어주면 된다.
}
// delete
@GetMapping("/kakao/delete") // mapping 주소 : onclick으로 넘겨준 주소.
public String delete(@RequestParam String num) {
dao.deleteCar(num);
return "redirect:list"; // mapping 주소를 가지고 있는 controller 를 통해서 이동하기 때문에 'car/carList'가 아니라 'redirect:list' 로 보내줘야 한다.
// 디스페쳐 서블릿이 컨트롤러에 가서 경로를 검색한다.
}
// update 1단계 : updateForm 띄우기
@GetMapping("/kakao/updateform")
public String uform(@RequestParam String num,Model model) {
MyCarDto dto=dao.getData(num);
model.addAttribute("dto", dto);
return "car/updateForm";
}
// update 2단계 : update 하기
@PostMapping("/kakao/update")
public String update(@ModelAttribute MyCarDto dto) {
dao.updateCar(dto);
return "redirect:list";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css2?family=Bagel+Fat+One&family=Dongle:wght@300&family=East+Sea+Dokdo&family=Gamja+Flower&family=Gowun+Dodum&family=Nanum+Gothic+Coding&family=Nanum+Pen+Script&family=Orbit&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<title>Insert title here</title>
</head>
<body>
<button type="button" class="btn btn-success" onclick="location.href='writeForm'">차 정보 입력</button>
<c:if test="${totalCount==0 }">
<h3 class="alert alert-info">저장된 차의 정보가 없습니다.</h3>
</c:if>
<c:if test="${totalCount>0 }">
<h3 class="alert alert-success">${totalCount }개의 자동자가 등록되었습니다.</h3>
</c:if>
<table class="table table-bordered" style="width: 700px;">
<tr>
<th width="60">번호</th>
<th width="160">차량 이름</th>
<th width="100">차량 색상</th>
<th width="160">차량 가격</th>
<th width="160">차량 구입 날짜</th>
<th width="200">편집</th>
</tr>
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td>${i.count }</td>
<td>${dto.carname }</td>
<td>
<div style="width: 20px; height: 20px; border-radius: 20px; background-color: ${dto.carcolor };" ></div>
</td>
<td>
<fmt:formatNumber value="${dto.carprice }" type="currency"/>
</td>
<td>${dto.carguip }</td>
<td>
<button type="button" class="btn btn-warning" onclick="location.href='updateform?num=${dto.num}'">수정</button>
<button type="button" class="btn btn-danger" onclick="location.href='delete?num=${dto.num}'">삭제</button>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
<body>
<div style="margin: 100px 50px;">
<form action="insert" method="post">
<table class="table table-bordered" style="width: 350px;">
<tr>
<th>고객명</th>
<td>
<input type="text" name="name" required="required" class="form-control">
</td>
</tr>
<tr>
<th>연락처</th>
<td>
<input type="text" name="hp" required="required" class="form-control">
</td>
</tr>
<tr>
<th>주소</th>
<td>
<input type="text" name="addr" required="required" class="form-control">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="btn btn-outline-warning">추가</button>
<button type="button" class="btn btn-outline-info" onclick="location.href='list'">목록</button>
</td>
</tr>
</table>
</form>
</div>
</body>
<body>
<div style="margin: 100px 50px;">
<form action="update" method="post">
<input type="hidden" name="num" value="${cardto.num }">
<table class="table table-bordered" style="width: 350px;">
<tr>
<th>고객명</th>
<td>
<input type="text" name="name" required="required" class="form-control" value="${cardto.name }">
</td>
</tr>
<tr>
<th>연락처</th>
<td>
<input type="text" name="hp" required="required" class="form-control" value="${cardto.hp }">
</td>
</tr>
<tr>
<th>주소</th>
<td>
<input type="text" name="addr" required="required" class="form-control" value="${cardto.addr }">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="btn btn-outline-warning">수정</button>
<button type="button" class="btn btn-outline-info" onclick="location.href='list'">목록</button>
</td>
</tr>
</table>
</form>
</div>
</body>