본문 바로가기
오답노트

Spring으로 방명록 만들기

by titlejjk 2023. 6. 20.

1. 방명록게시판에 만들 각각의 Controller와 Dao, Dto 만들기

 

<?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="guest">

	
</mapper>

SQL문을 작성할 GuestMapper.xml을 만들어 주고 코드 초기화 해주기.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- sql 문을 작성한 Mapper xml 문서가 어디에 있는지 목록을 적성해야 한다. -->
	<mappers>
		<mapper resource="mapper/MemberMapper.xml"/>
		<mapper resource="mapper/GuestMapper.xml"/>
	</mappers>
</configuration>

Configuration.xml에서 SQL문을 작성한 Mapper.xml문서가 어디에 있는지 작성해주기.

방명록에 사용할 각 jsp페이지 만들어주기.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/home.jsp</title>
</head>
<body>
	<div class="container">
		<h1>인덱스 페이지 입니다.</h1>
		<ul>
			<li><a href="member/list">회원목록보기</a></li>
			<li><a href="guest/list">방명록 보기</a></li>
		</ul>
		<img src="${pageContext.request.contextPath }/resources/images/kim1.png" />
		<h2>공지사항</h2>
		<ul>
			<c:forEach var="tmp" items="${requestScope.noticeList }" >
				<li>${tmp }</li>
			</c:forEach>
		</ul>
	</div>
</body>
</html>

view/home.jsp에 방명록의 목록을 볼수 있는 list.jsp페이지를 연결시켜준다.

그 다음으로 guset/list.jsp로 가서 list.jsp안에 목록을 읽어올 수 있도록 코드를 작성해 준다.

GuestDto 만들기

package com.gura.spring02.guest.dto;

public class GuestDto {
	private int num;
	private String writer;
	private String content;
	private String pwd;
	private String regdate;
	
	public GuestDto() {}

	public GuestDto(int num, String writer, String content, String pwd, String regdate) {
		super();
		this.num = num;
		this.writer = writer;
		this.content = content;
		this.pwd = pwd;
		this.regdate = regdate;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getWriter() {
		return writer;
	}

	public void setWriter(String writer) {
		this.writer = writer;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getRegdate() {
		return regdate;
	}

	public void setRegdate(String regdate) {
		this.regdate = regdate;
	}
	
	
}

 

GuestDao 인터페이스만들기

package com.gura.spring02.guest.dao;

import java.util.List;

import com.gura.spring02.guest.dto.GuestDto;

public interface GuestDao {
	
	public void insert(GuestDto dto);
	public void update(GuestDto dto);
	public void delete(int num);
	public GuestDto getDate(int num);
	public List<GuestDto> getList();
}

인터페이스는 구현할 클래스의 메소드를 강제하는 것.

 

 

GuestDaoImpl 클래스만들어주기

package com.gura.spring02.guest.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gura.spring02.guest.dto.GuestDto;



@Repository
public class GuestDaoImpl implements GuestDao{

	@Autowired
	private SqlSession session;
	
	@Override
	public void insert(GuestDto dto) {
		
		session.insert("guest.insert", dto);
	}

	@Override
	public void update(GuestDto dto) {
		session.update("geust.update", dto);
	}

	@Override
	public void delete(int num) {
		session.delete("guest.delete", num);
	}

	@Override
	public GuestDto getDate(int num) {
		/*
		 *	Mapper's namespace => guest
		 * 	sql's id => getData
		 * 	parameterType => int
		 * 	resultType => GuestDto
		 */
		return session.selectOne("guest.getData", num);
	}

	@Override
	public List<GuestDto> getList() {
		/*
		 *	Mapper's namespace => guest
		 *	sql's id => getList
		 *	parameterType => X
		 *	resultType => GuestDto
		 */
		List<GuestDto> list = session.selectList("guest.getList");
		return list;
	}

}

GuestDao의 미완성인 메소드(추상메소드)들을 implements해서 Override한다.

mybatis 기반으로 DB연동을 하기 위한 핵심 의존객체를 Dependency Inecion 받는다.

@

@Autowired
private SqlSession session;

Mapper에서 경로 설정해주고

GuestMapper를 완성해준다.

<?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="guest">
	
	<select id="getData" parameterType="int" resultType ="com.gura.spring02.guest.dto.GuestDto">
		SELECT num, writer, content, pwd, regdate
		FROM board_guest
		WHERE num = #{num}
	</select>
	
	<update id="update" parameterType="com.gura.spring02.guest.dto.GuestDto">
		UPDATE board_guest
		SET writer=#{writer}, content = #{content}
		WHERE num = #{num} AND pwd=#{pwd}
	</update>
	
	<delete id="delete" parameterType = "com.gura.spring02.guest.dto.GuestDto">
		DELETE FROM board_guest
		WHERE num = #{num} AND pwd = #{pwd}
	</delete>
	
	<select id="getList" resultType="com.gura.spring02.guest.dto.GuestDto">
		SELECT num, writer, content, pwd, regdate
		FROM board_guest
		ORDER BY num ASC
	</select>
	<insert id="insert" parameterType="com.gura.spring02.guest.dto.GuestDto">
		INSERT INTO board_guest(num, writer, content, pwd, regdate)
		VALUES(board_guest_seq.NEXTVAL,
		 #{writer}, #{content}, #{pwd}, SYSDATE)
	</insert>
</mapper>

 

GuestController생성

package com.gura.spring02.guest.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gura.spring02.guest.dao.GuestDao;
import com.gura.spring02.guest.dto.GuestDto;

@Controller
public class GuestController {

	//Controller가 필요로 하는 핵심의존객체 생성
	@Autowired
	private GuestDao dao;
	
	@RequestMapping("/guest/list")
	public String list(HttpServletRequest request) {
		List<GuestDto> list = dao.getList();
		request.setAttribute("list", list);
		return "guest/list";
	}
	
	//방명록작성 요청처리
	@RequestMapping("/guest/insert")
	public String insert(GuestDto dto) {
		dao.insert(dto);
		return "guest/insert";
	}
	
	//방명록작성폼 요청 처리
	@RequestMapping("/guest/insertform")
	public String insertform() {
		return "guest/insertform";
	}
	
	//방명록삭제 요청처리
	@RequestMapping("/guest/delete")
	public String delete(@RequestParam(value="num", defaultValue = "0")int num) {
		dao.delete(num);
		return "redirect:/guest/list";
	}
	
}

메인 list page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/views/guest/list.jsp</title>
</head>
<body>
	<div class = "container">
		<h1>방명록 글 목록</h1>
		<div>
			<a href="${pageContext.request.contextPath}/guest/insertform">글작성</a>
		</div>
		<table>
			<thead>
				<tr>
					<th>글번호</th>
					<th>작성자</th>
					<th>내 용</th>
					<th>등록일</th>
					<th>삭 제</th>
				</tr>
			</thead>
			<tbody>
				<c:forEach var = "tmp" items ="${list }">
					<tr>
						<td>${tmp.num }</td>
						<td>${tmp.writer }</td>
						<td><textarea rows="5">${tmp.content }</textarea></td>
						<td>${tmp.regdate }</td>
						<td><a href="updateform?num=${tmp.num }">수정</a></td>
						<td><a href="delete?num=${tmp.num }">삭제</a></td>
					</tr>
				</c:forEach>
			</tbody>
		</table>
	</div>
</body>
</html>

댓글