겉바속촉
[spring] 게시판 만들어보기 본문
2020/06/29 - [취업일기/SPRING] - [spring] MyBatis 깔고 setting해주기
지난번 포스팅대로 setting이 끝나셨다면 이제 정말로 게시판을 만들어볼게유:)
다음순서대로 작성해주셔야합니다
로직을 이해하면서 왜 이런코드가 나오는 건지 보면서 작성해주세요~
1. writeForm.jsp
우선 게시판에 글을 쓸 수 있는 폼인 writeForm을 만들어줄게요:)
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<h1></h1>
<form action="" method="post">
<table class="table table-striped" style="width: 400px;">
<caption><b>글쓰기</b></caption>
<tr>
<th>작성자</th>
<td>
<input type="text" name="writer" style="width: 100px"
class="form-control input-sm">
</td>
</tr>
<tr>
<th>제목</th>
<td>
<input type="text" name="subject" style="width: 300p;"
class="form-control input-sm" >
</td>
</tr>
<tr>
<td colspan="2">
<textarea style="width: 400px; height: 150px;"
name="content" class="form-control">
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="btn btn-info">db에 저장</button>
</td>
</tr>
</table>
</form>
</body>
</html>
2. list.jsp
우리가 가장 먼저 보는 화면 즉 게시판의 리스트를 작성해주셔야합니다.
또한 제목 누르면 content가 뜨도록 코드를 작성해줄게요:)
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<span class="alert alert-danger">
<b>총 ${totalCount}개의 데이타가 있습니다</b>
</span>
<br>
<button type="button" class="btn btn-info"
onclick="location.href='writeform'" style="margin-left: 400px;">글쓰기</button>
<hr>
<div class="container">
<table class="table table-bordered" style="width: 700px;" >
<tr>
<th width="50">번호</th>
<th width="200">제목</th>
<th width="80">작성자</th>
<th width="120">작성일</th>
</tr>
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td align="center">${i.count}</td>
<td><a href="content?num=${dto.num }">${dto.subject }</a></td>
<td>${dto.writer }</td>
<td><fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd"/></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
3. BoardDaointer.java
package board.data;
public interface BoardDaointer {
public int getTotalCount();
public void insertBoard(BoardDto dto);
}
4. BoardSql.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="board">
<select id="selectCountOfBoard" resultType="int">
select count(*) from board
</select >
<insert id="insertOfBoard" parameterType="bdto">
insert into board values(seq_b.interval,#{writer}, #{subject},#{content},sysdate)
</insert>
</mapper>
5. BoardDao.java
package board.data;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class BoardDao extends SqlSessionDaoSupport implements BoardDaointer{
@Override
public int getTotalCount() {
return getSqlSession().selectOne("selectCountOfBoard");
}
@Override
public void insertBoard(BoardDto dto)
{
//dao에서 dto를 넘기는 것
getSqlSession().insert("insertOfBoard", dto);
}
}
6. BoardController.java
package spring.mvc.board;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import board.data.BoardDaointer;
import board.data.BoardDto;
@Controller
public class BoardController {
@Autowired
private BoardDaointer dao;
@GetMapping("/list") //index시작 경로와 같다
public ModelAndView list()
{
ModelAndView model=new ModelAndView();
int totalCount=dao.getTotalCount();
model.addObject("totalCount", totalCount);
model.setViewName("board/list");
return model;
}
@PostMapping("/write")
public String insert(@ModelAttribute BoardDto dto)
{
dao.insertBoard(dto);
return "redirect:list";
}
}
7. BoardDaointer.java
package board.data;
import java.util.List;
public interface BoardDaointer {
public int getTotalCount();
public void insertBoard(BoardDto dto);
public List<BoardDto> getAllDatas();
}
8. BoardSql.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="board">
<select id="selectCountOfBoard" resultType="int">
select count(*) from board
</select>
<insert id="insertOfBoard" parameterType="bdto">
insert into board values(seq_b.nextval,#{writer},#{subject},#{content},sysdate)
</insert>
<select id="selectAllOfBoard" resultType="bdto">
select * from board order by num asc
</select>
</mapper>
9. BoardDao.java
package board.data;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class BoardDao extends SqlSessionDaoSupport implements BoardDaointer{
@Override
public int getTotalCount() {
return getSqlSession().selectOne("selectCountOfBoard");
}
@Override
public void insertBoard(BoardDto dto)
{
//dao에서 dto를 넘기는 것
getSqlSession().insert("insertOfBoard", dto);
}
public List<BoardDto> getAllDatas() {
return getSqlSession().selectList("selectAllOfBoard");
}
}
10. BoardController.java
package spring.mvc.board;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import board.data.BoardDaointer;
import board.data.BoardDto;
@Controller
public class BoardController {
@Autowired
private BoardDaointer dao;
@GetMapping("/list") //index시작 경로와 같다
public ModelAndView list()
{
ModelAndView model=new ModelAndView();
int totalCount=dao.getTotalCount();
List<BoardDto> list=dao.getAllDatas();
model.addObject("totalCount", totalCount);
model.addObject("list", list);
model.setViewName("board/list");
return model;
}
@PostMapping("/write")
public String insert(@ModelAttribute BoardDto dto)
{
dao.insertBoard(dto);
return "redirect:list";
}
}
위의 순서대로 작성하신 후에
컴파일 해주세요:)
여기까지 나왔다면 성공!^^!
11. 이제 글쓰기 버튼을 눌렀을 때 글을 작성할 수 있는 form이 떠야합니다
그럼 BoardController에 들어가셔서 코드를 추가작성해주세요:)
다음부분을 추가해주시면 됩니다
@GetMapping("/writeform") //리스트의 글쓰기버튼
public String writeform()
{
return "board/writeForm";
}
BoardController 전체코드
package spring.mvc.board;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
import board.data.BoardDaointer;
import board.data.BoardDto;
@Controller
public class BoardController {
@Autowired
private BoardDaointer dao;
//리스트 출력문이 나오는 페이지
@GetMapping("/list") //index시작 경로와 같다
public ModelAndView list()
{
ModelAndView model=new ModelAndView();
int totalCount=dao.getTotalCount();
List<BoardDto> list=dao.getAllDatas();
model.addObject("totalCount", totalCount);
model.addObject("list", list);
model.setViewName("board/list");
return model;
}
//폼에 입력시 insert되는 페이지
@PostMapping("/write") //폼의 액션과 일치
public String insert(@ModelAttribute BoardDto dto)
{
dao.insertBoard(dto);
return "redirect:list";
}
//리스트의 글쓰기 버튼을 클릭했을 때 폼이 나오도록 매핑처리
@GetMapping("/writeform") //리스트의 글쓰기버튼
public String writeform()
{
return "board/writeForm";
}
}
그리고 컴파일 하신 후에 글쓰기 클릭하시면 다음과 같이 뜹니다:)
내용입력하신 후에 db에 저장을 누르면 list에 떠야합니다
그런데 저는 한글이 깨지고 있네요:)
혹시 깨지시는 분이 있다면
다음 코드를 web.xml 아무곳에나 추가해주시면 okay~
<!-- encoding -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
그리고 서버 껐다가 다시 키고 실행해주세요~~
다음과 같이 나오네요!^^!
한글 깨짐없이 list로 잘 옮겨졌습니다
이제 우리는 list의 제목을 누르면 content가 뜨게 해줄거에요:)
list.jsp에 추가
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td align="center">${i.count}</td>
<td><a href="content?num=${dto.num }">${dto.subject }</a></td>
<td>${dto.writer }</td>
<td><fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd"/></td>
</tr>
</c:forEach>
전체 list.jsp
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<span class="alert alert-danger">
<b>총 ${totalCount}개의 데이타가 있습니다</b>
</span>
<br>
<button type="button" class="btn btn-info"
onclick="location.href='writeform'" style="margin-left: 400px;">글쓰기</button>
<hr>
<div class="container">
<table class="table table-bordered" style="width: 700px;" >
<tr>
<th width="50">번호</th>
<th width="200">제목</th>
<th width="80">작성자</th>
<th width="120">작성일</th>
</tr>
<c:forEach var="dto" items="${list }" varStatus="i">
<tr>
<td align="center">${i.count}</td>
<td><a href="content?num=${dto.num }">${dto.subject }</a></td>
<td>${dto.writer }</td>
<td><fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd"/></td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
BoardDaointer.java에 추가 작성해서 전체 코드
package board.data;
import java.util.List;
public interface BoardDaointer {
public int getTotalCount();
public void insertBoard(BoardDto dto);
public List<BoardDto> getAllDatas();
public BoardDto getData(String num);
}
BoardSql.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="board">
<select id="selectCountOfBoard" resultType="int">
select count(*) from board
</select>
<insert id="insertOfBoard" parameterType="bdto">
insert into board values(seq_b.nextval,#{writer},#{subject},#{content},sysdate)
</insert>
<select id="selectAllOfBoard" resultType="bdto">
select * from board order by num asc
</select>
<select id="selectOneOfBoard" parameterType="String" resultType="bdto">
select * from board where num=#{num}
</select>
</mapper>
BoardDao.java
package board.data;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
@Repository
public class BoardDao extends SqlSessionDaoSupport implements BoardDaointer{
@Override
public int getTotalCount() {
return getSqlSession().selectOne("selectCountOfBoard");
}
@Override
public void insertBoard(BoardDto dto)
{
//dao에서 dto를 넘기는 것
getSqlSession().insert("insertOfBoard", dto);
}
@Override
public List<BoardDto> getAllDatas() {
return getSqlSession().selectList("selectAllOfBoard");
}
@Override
public BoardDto getData(String num) {
return getSqlSession().selectOne("selectOneOfBoard",num);
}
}
content.jsp
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
작성자: ${dto.writer }<br>
작성일: <fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/><br>
제목: ${dto.subject }<br>
내용:
<pre>${dto.content }</pre>
<button type="button" class="btn btn-success"
onclick="location.href='writeform'">글쓰기</button>
<button type="button" class="btn btn-success"
onclick="location.href='list'">목록</button>
<button type="button" class="btn btn-success"
onclick="location.href='updateform?num=${dto.num}'">수정</button>
<button type="button" class="btn btn-success"
onclick="location.href='delete?num=${dto.num}'">삭제</button>
</body>
</html>
BoardController.java에 추가 작성해서 전체 코드
package spring.mvc.board;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
import board.data.BoardDaointer;
import board.data.BoardDto;
@Controller
public class BoardController {
@Autowired
private BoardDaointer dao;
//리스트 출력문이 나오는 페이지
@GetMapping("/list") //index시작 경로와 같다
public ModelAndView list()
{
ModelAndView model=new ModelAndView();
int totalCount=dao.getTotalCount();
List<BoardDto> list=dao.getAllDatas();
model.addObject("totalCount", totalCount);
model.addObject("list", list);
model.setViewName("board/list");
return model;
}
//폼에 입력시 insert되는 페이지
@PostMapping("/write") //폼의 액션과 일치
public String insert(@ModelAttribute BoardDto dto)
{
dao.insertBoard(dto);
return "redirect:list";
}
//리스트의 글쓰기 버튼을 클릭했을 때 폼이 나오도록 매핑처리
@GetMapping("/writeform") //리스트의 글쓰기버튼
public String writeform()
{
return "board/writeForm";
}
//리스트에서 제목을 누르면 content로 연결되도록 매핑
@GetMapping("/content") //리스트의 제목에 a태그로 연결된 이름
public ModelAndView content(@RequestParam String num)
{
ModelAndView model=new ModelAndView();
BoardDto dto=dao.getData(num);
model.addObject("dto", dto);
model.setViewName("board/content");
return model;
}
}
이제 Run As 해보시면 다음과 같이 뜹니다:)
저기서 마리아를 클릭해볼게요:)
content까지 잘 뜨는 게 보이시쥬?
이제는 수정, 삭제 ---> update랑 deleter 기능까지 추가해볼게요
content.jsp 추가 작성해서 전체코드
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
작성자: ${dto.writer }<br>
작성일: <fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/><br>
제목: ${dto.subject }<br>
내용:
<pre>${dto.content }</pre>
<button type="button" class="btn btn-success"
onclick="location.href='writeform'">글쓰기</button>
<button type="button" class="btn btn-success"
onclick="location.href='list'">목록</button>
<button type="button" class="btn btn-success"
onclick="location.href='updateform?num=${dto.num}'">수정</button>
<button type="button" class="btn btn-success"
onclick="location.href='delete?num=${dto.num}'">삭제</button>
</body>
</html>
updateForm.jsp 만들어 준 후에 ----> writeForm.jsp에서 body 블럭 복붙해서 고쳐주기
<%@ 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">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Insert title here</title>
</head>
<body>
<h1></h1>
<form action="update" method="post">
<table class="table table-striped" style="width: 400px;">
<caption><b>글쓰기</b></caption>
<tr>
<th>작성자</th>
<td>
<input type="text" name="writer" style="width: 100px"
class="form-control input-sm" value="${dto.writer }">
</td>
</tr>
<tr>
<th>제목</th>
<td>
<input type="text" name="subject" style="width: 300p;"
class="form-control input-sm" value="${dto.subject }">
</td>
</tr>
<tr>
<td colspan="2">
<textarea style="width: 400px; height: 150px;"
name="content" class="form-control">
${dto.content }
</textarea>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<!-- num hidden으로 넘기기 -->
<input type="hidden" name="num" value="${dto.num }">
<button type="submit" class="btn btn-info">db수정</button>
</td>
</tr>
</table></form>
</body>
</html>
저는 아까 한글 깨졌던 부분을 수정해줄게요
수정 클릭
그럼 우리가 수정해주려고 누른 사람의 현재 정보들이 그대로 폼에 노출되어있어야 맞습니다!!
이제 선미의 보랏빛 밤을 넣고 db수정을 눌러주면 저 정보들로 고쳐졌으면 좋겠쥬?!
BoardSql.xml에 추가해주세요
<update id="updateOneOfBoard" parameterType="bdto">
update board set writer=#{writer}, subject=#{subject}, content=#{content} where num=#{num}
</update>
BoardDao.java로 가셔서 추가해주세요
@Override
public void updateBoard(BoardDto dto) {
getSqlSession().update("updateOneOfBoard",dto);
}
그리고 BoardController.java로 가주셔야겠쥬?
//수정한 후 db수정 누르면 수정되기
@GetMapping("/update")
public String update(@ModelAttribute BoardDto dto)
{
dao.updateBoard(dto);
return "redirect:list";
}
이제 컴파일해볼게요
보라돌이를 선미 보랏빛 밤으로 수정했습니다:)
수정도 잘 되고 페이지도 잘 넘어가는 지 확인해주세요!!
삭제해주기
BoardDaoInter.java로 가주세요
deleteBoard 추가할게요:)
package board.data;
import java.util.List;
public interface BoardDaointer {
public int getTotalCount();
public void insertBoard(BoardDto dto);
public List<BoardDto> getAllDatas();
public BoardDto getData(String num);
public void updateBoard(BoardDto dto);
public void deleteBoard(String num);
}
그럼 이제 BoardSql.xml로 가서 다음을 추가해주세요
<delete id="deleteOfBoard" parameterType="String">
delete from board where num=#{num}
</delete>
BoardDao.java에서 또 추가해주셔야겠죠?!
@Override
public void deleteBoard(String num) {
getSqlSession().delete("deleteOfBoard",num);
}
그리고 컴파일해서
아까 한글 깨졌던 게시물을 클릭해서 삭제해줄게요:)
'IT일기(하반기) > SPRING' 카테고리의 다른 글
[spring] 게시판만들기2-수정삭제편 (0) | 2020.07.01 |
---|---|
[spring] 게시판 만들기 2 (1) | 2020.06.30 |
[spring] MyBatis 깔고 setting해주기 (2) | 2020.06.29 |
[spring] 이미지 띄우기 (0) | 2020.06.26 |
[Spring] 폼 만들어서 데이터 받아오기 (2) | 2020.06.26 |