겉바속촉

[spring] 사이트 만들기 -게시판 편 본문

IT일기(하반기)/SPRING

[spring] 사이트 만들기 -게시판 편

겉바속촉 2020. 7. 8. 17:44
728x90
반응형

 

BoardDto

package board.data;

import java.sql.Timestamp;

public class BoardDto {
	
	private int num;
	private String writer;
	private String subject;
	private String content;
	private int readcount;
	private Timestamp writeday;
	
	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 getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getReadcount() {
		return readcount;
	}
	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}
	public Timestamp getWriteday() {
		return writeday;
	}
	public void setWriteday(Timestamp writeday) {
		this.writeday = writeday;
	}
	
	

}

 

SqlMapConfig로 가셔서 추가해주세요

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig 3.0//EN" "HTTP://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <typeAliases>
    <typeAlias type="info.data.InfoDto" alias="idto"/>
    <typeAlias type="member.data.MemberDto" alias="mdto"/>
    <typeAlias type="board.data.BoardDto" alias="bdto"/>
  </typeAliases>
  
  <mappers>
    <mapper resource="mybatis/setting/InfoSql.xml"/>
    <mapper resource="mybatis/setting/MemberSql.xml"/>
    <mapper resource="mybatis/setting/BoardSql.xml"/>
    
  </mappers>
</configuration>

 

 

BoardSql

<?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="TotalCountOfBoard" resultType="int">
		select count(*) from springboard	
	</select>
</mapper>

 

BoardDaoInter

package board.data;

public interface BoardDaoInter {
	
	public int getTotalCount();

}

 

BoardDao

 

1. extends _SqlSessionDaoSupport

2. implements _BoardDaoInter

3. 추상메서드 받기

4. @Repository

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() {
		// TODO Auto-generated method stub
		int n=getSqlSession().selectOne("TotalCountOfBoard");
		return n;
	}

}

 

BoardController

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.servlet.ModelAndView;

import board.data.BoardDaoInter;

@Controller
public class BoardController {

		@Autowired
		BoardDaoInter dao;
	
		
		//게시판 출력
		@GetMapping ("/board/list") //메뉴에서 시작하니 매핑주소 맞출것
		public ModelAndView list()
		{
			ModelAndView model=new ModelAndView();
			int totalCount=dao.getTotalCount();
			model.addObject("totalCount", totalCount);
			model.setViewName("/board/boardList");
			
			return model;
		}
	
}

 

BoardList

<%@ 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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<div class="alert alert-success">
	총<strong>${totalCount}</strong>개의 글이 있습니다
</div>

<div>
<button class="btn btn-danger btn-sm" style="font-size: 18px; width: 100px;" 
onclick="location.href='${path}/board/writeform'">글쓰기</button>
</div>
</body>

</html>

 

게시판 눌러보시면 다음과 같이 떠야합니다:)

 

 

 

 

이제는 글쓰기 버튼을 눌렀을 때

boardForm이 뜨도록 해볼게요:)

 

 

boardForm

<%@ 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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<form action="write" method="post">
	<table class="table table-striped" style="width: 400px;">
		<caption>게시판 글쓰기</caption>
		<tr>
			<th>작성자</th>
			<td>
				<input type="text" name="writer" class="form-control">
			</td>
		</tr>
		
		<tr>
			<th>제목</th>
			<td>
				<input type="text" name="subject" class="form-control">
			</td>
		</tr>
		
		<tr>
			<td colspan="2">
				<textarea rows="10" cols="40" name="content"
				class="form-control">				
				</textarea>
			</td>
		</tr>
		
		<tr>			
			<td colspan="2" align="center">
				<button class="btn btn-default btn-lg">저장하기</button>
			</td>
		</tr>
		
	</table>
</form>
</body>
</html>

 

 

 

그럼 다음과 같이 뜹니다:)


Insert

 

 

 


 

 

페이징처리에 필요한 리스트 작업해주기

 

 

 

BoardSql에 다음 추가

<select id="selectpagingofboard" parameterType="HashMap" resultType="bdto">
  <![CDATA[
   select a.* from (select ROWNUM as RNUM,b.* from
   (select * from springboard order by num desc)b)a
   where a.RNUM>=#{start} and a.RNUM<=#{end}
  ]]>
 </select>

BoardDao

parameterType으로 받는 것이 두개라면 map으로 해주세요

 

 

그리고 Controller의 게시판 출력부분에서 @RequestParam으로 받을게요

@GetMapping ("/board/list") //메뉴에서 시작하니 매핑주소 맞출것
		public ModelAndView list(@RequestParam(value="pageNum",defaultValue="1")int currentPage)
		{
			ModelAndView model=new ModelAndView();
			int totalCount=dao.getTotalCount();
			model.addObject("totalCount", totalCount);
			model.setViewName("/board/boardList");
			
			return model;
		}

그리고 dao에서 getTotalCount해준 다음 줄부터 추가로 작성하셔야합니다

이제 페이징 처리를 해주는 코드를 만드는 거쥬!!

 

	//페이징처리에 필요한 변수
			int totalPage; //총 페이지 수
			int startNum; //각 페이지의 시작번호
			int endNum; //각 페이지의 끝번호
			int startPage; //블럭의 시작페이지
			int endPage; //블럭의 끝페이지
			int no; //출력할 시작번호
			int perPage=5; //한 페이지당 보여질 글의 갯수
			int perBlock=5; //한 페이지당 보여질 페이지의 갯수
			
			//총 페이지의 수를 구한다
			totalPage=totalCount/perPage+(totalCount%perPage>0?1:0);
			
			//존재하지 않는 페이지일 경우 마지막페이지로 가기
			if(currentPage>totalPage)
				currentPage=totalPage;
			
			//각 블럭의 시작페이지와 끝페이지 구하기
			//perBlock이 5일 경우
			//예: 한페이지가 3일 경우 시작페이지 1 끝 5
			//예: 한페이지가 7일 경우 시작페이지 6 끝 10
			//예: 한페이지가 11일 경우 시작페이지 11 끝 15
			
			startPage=(currentPage-1)/perBlock*perBlock+1;
			endPage=startPage+perBlock-1;
			//마지막블럭은 끝페이지가 총 페이지수와 같아야함
			if(endPage>totalPage)
				endPage=totalPage;
			
			//각 페이지의 시작번호와 끝 번호 구하기
			//perPage가 5일 경우
			//예: 1페이지: 시작번호:1  끝번호:5
			//예: 3페이지: 시작번호:1  끝번호:15
			startNum=(currentPage-1)*perPage+1;
			endNum=startNum+perPage-1;
			
			//마지막 페이지의 글번호 체크
			if(endNum>totalCount)
				endNum=totalCount;
                //각페이지마다 출력할 시작번호
			//총페이지가 30일 경우 1페이지는 30, 2페이지는 25.....
			no=totalCount-(currentPage-1)*perPage;
			
			//리스트 가져오기
			List<BoardDto>list=dao.getList(startNum, endNum);
			
			//페이징에 필요한 변수들 request로 저장...
			model.addObject("list", list);
			model.addObject("currentPage", currentPage);
			model.addObject("startPage", startPage);
			model.addObject("endPage", endPage);
			model.addObject("no", no);
			model.addObject("totalPage", totalPage);				
			model.addObject("totalCount", totalCount);
			model.setViewName("/board/boardList");
			
			return model;
		}
		
						
			

 

 

글쓰기를 통해서 데이터를 좀 넣어주신 후에

페이징 처리 해준 부분이 다음과 같이 잘 뜨는 지 확인해주세요:)

 

 

boardList

<%@ 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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<div class="alert alert-success">
	총<strong>${totalCount}</strong>개의 글이 있습니다
</div>

<div>
<button class="btn btn-danger btn-sm" style="font-size: 18px; width: 100px;" 
onclick="location.href='${path}/board/writeform'">글쓰기</button>
</div>

<table class="table table-bordered">
	<caption>게시판 목록</caption>
		<tr>
			<th style="width: 60px;">번호</th>
			<th style="width: 300px;">제목</th>
			<th style="width: 60px;">작성자</th>
			<th style="width: 60px;">조회</th>
			<th style="width: 120px;">작성일</th>
		</tr>
		<c:forEach var="dto" items="${list }">
		<tr>
			<td align="center">${no }</td>
			<c:set var="no" value="${no-1 }"/>
			<td>
			<a href="content?num=${dto.num }&pageNum=${currentPage}">${dto.subject }</a>
			</td>
			<td align="center">${dto.writer }</td>
			<td align="center">${dto.readcount }</td>
			<td align="center">
			<fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/>
			</td>
			
			
		</tr>
		</c:forEach>
</table>


<!-- 요기에 페이징 처리  -->

<div style="width:1000px; text-align: center;">
	<ul class="pagination">
		<c:if test="${startPage>1 }">
			<li>
				<a href="list?pageNum=${startPage-1 }">◀ </a>
			
			</li>		
		</c:if>
	
	<c:forEach var="pp" begin="${startPage }" end="${endPage }">
		<li>
			<c:if test="${pp==currentPage }">
				<a href="list?pageNum=${pp}" style="color: red;">${pp }</a>
			</c:if>
			<c:if test="${pp!=currentPage }">
				<a href="list?pageNum=${pp}" style="color: black;">${pp }</a>
			</c:if>
		
		</li>
	
	</c:forEach>
	
	<c:if test="${endPage<totalPage }">
			<li>
				<a href="list?pageNum=${endPage+1 }">▶ </a>
			
			</li>
		
		</c:if>
	
	
	
	</ul>
</div>






</body>

</html>

 

출력화면

 


 

조회수 작업하기

 

 

BoardDaoInter

 

 

 

BoardSql

 

 

 

BoardDao

 

 

content.jsp 만들어주기

 

 

 

 

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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<table style="width: 500px;" class="table table-bordered">
	<tr>
		<th>
			${dto.subject }
			<span style="margin-left: 200px; color: gray;">
				<fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/>
			</span>
		</th>
	</tr>
	<tr>
		<td>
		작성자: ${dto.writer }
			<span style="margin-left: 300px; color: gray">조회: ${dto.readcount }</span>
			<br>
			<pre><span>${dto.content }</span></pre>
		</td>	
	</tr>
</table>
<!-- 수정,삭제,목록 버튼들 -->

<div>
<button type="button" class="btn btn-info btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/list?pageNum=${pageNum }'">목록</button>

<button type="button" class="btn btn-danger btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/writeform?pageNum=${pageNum }'">글쓰기</button>

<button type="button" class="btn btn-success btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/updateform?num=${dto.num }&pageNum=${pageNum }'">수정</button>

<button type="button" class="btn btn-info btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/delete?num=${dto.num }&pageNum=${pageNum }'">삭제</button>

</div>
</body>
</html>

 

Controller

 

 

 

 

레드벨벳의 psycho를 클릭하면 다음과 같이 뜹니다:)

 

 

그리고 다음과 같이 조회수가 증가했는 지 확인해주세요:)


삭제 작업하기

 

DaoInter

 

BoardSql

 

 

BoardDao

 

BoardController

 

 

 

 

그런데 여태까지 해준 삭제 작업은

다른 페이지의 글을 지워도 1페이지로 돌아가기 때문에

그 부분을 보완해주셔야합니다:)

 

예를들어서 4페이지의 글 중 하나를 지워주었다면 4페이지에 머물러줄 수 있게 해주셔야된단 말이쥬

 

 

Controller에서 다음과 같이 추가로 넣어주시면 okay

 


수정 작업해주기

 

BoardDaoInter

 

 

BoardSql

 

BoardDao

 

BoardController

 

updateForm 만들어주기

<%@ 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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<form action="update" method="post">
	<table class="table table-striped" style="width: 400px;">
		<caption>게시판 글쓰기</caption>
		<tr>
			<th>작성자</th>
			<td>
				<input type="text" name="writer" class="form-control" value="${dto.writer }">
			</td>
		</tr>
		
		<tr>
			<th>제목</th>
			<td>
				<input type="text" name="subject" class="form-control" value="${dto.subject }">
			</td>
		</tr>
		
		
		<tr>
			<td colspan="2">
				<textarea rows="10" cols="40" name="content"
				class="form-control">	
				${dto.content }			
				</textarea>
			</td>
		</tr>
		
		<tr>			
			<td colspan="2" align="center">
			<input type="hidden" name="num" value="${dto.num }" />
			<input type="hidden" name="pageNum" value="${pageNum }">
				<button class="btn btn-default btn-lg"
				type="submit">수정하기</button>
			</td>
		</tr>
		
	</table>
</form>
</body>
</html>

 

 

여기서 잠깐!!! 

아까 삭제 작업처럼 여태까지 해준 수정 작업은

다른 페이지의 글을 지워도 1페이지로 돌아가기 때문에

그 부분을 보완해주셔야합니다:)

 

예를들어서 4페이지의 글 중 하나를 수정해주었다면 4페이지에 머물러줄 수 있게 해주셔야된단 말이쥬

 

 

Controller에서 다음과 같이 추가로 넣어주시면 okay

 

 

 

 

이제 실행해볼게요:)

4페이지의 조정석 아로하를 수정해보도록 할게요

 

거미 빠로하라고 적고 수정 클릭

 

 


 

전체 코드들

 

menu.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" %>
<%@taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>

<!DOCTYPE html>
<html>
<head>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<a href="${path }/home">Home </a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="${path }/info/insertform">입력폼</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="${path }/info/list">목록</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="${path }/member/insertform">회원가입</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="${path }/member/list">회원목록</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href="${path }/login/login">
	<c:if test="${sessionScope.loginok==null }">로그인&nbsp;&nbsp;</c:if>
	<c:if test="${sessionScope.loginok!=null }">로그아웃</c:if>
</a>&nbsp;&nbsp;&nbsp;&nbsp;
<c:if test="${sessionScope.loginok!=null }">
  <b style="color: red;">${sessionScope.idok}</b>님이 로그인중
</c:if>

<a href="${path }/board/list">게시판</a>&nbsp;&nbsp;&nbsp;&nbsp;

</body>
</html>

 

BoardDto.java

package board.data;

import java.sql.Timestamp;

public class BoardDto {
	
	private int num;
	private String writer;
	private String subject;
	private String content;
	private int readcount;
	private Timestamp writeday;
	
	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 getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public int getReadcount() {
		return readcount;
	}
	public void setReadcount(int readcount) {
		this.readcount = readcount;
	}
	public Timestamp getWriteday() {
		return writeday;
	}
	public void setWriteday(Timestamp writeday) {
		this.writeday = writeday;
	}
	
	

}

 

BoardDaoInter.java

package board.data;

import java.util.List;

public interface BoardDaoInter {
	
	public int getTotalCount();
	public void insertBoard(BoardDto dto);
	public List<BoardDto> getList(int start, int end);
	public void updateReadcount(int num);
	public BoardDto getData(int num);
	public void deleteBoard(int num);
	public void updateBoard(BoardDto dto);
	
}



 

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="TotalCountOfBoard" resultType="int">
    select count(*) from springboard
  </select>
  
  <insert id="InsertOfBoard" parameterType="bdto">
	insert into springboard values(seq_b.nextval,#{writer},#{subject},#{content},0,sysdate)
  </insert>
  
  <select id="selectpagingofboard" parameterType="HashMap" resultType="bdto">
  <![CDATA[
   select a.* from (select ROWNUM as RNUM,b.* from
   (select * from springboard order by num desc)b)a
   where a.RNUM>=#{start} and a.RNUM<=#{end}
  ]]>
 </select>
 
 <update id="boardUpdateReadcount" parameterType="int">
 	update springboard set readcount=readcount+1 where num =#{num}
 </update>
 
 <select id="selectOneOfBoard" parameterType="int" resultType="bdto">
 	select * from springboard where num=#{num}
 </select>
 
 <delete id="deleteOfBoard" parameterType="int">
 	delete from springboard where num=#{num}
 </delete>
 
 <update id="updateOfBoard" parameterType="bdto">
	update springboard set writer=#{writer}, subject=#{subject}, content=#{content} where num=#{num} 
 </update>
  
  
  
</mapper>

 

BoardDao.java

package board.data;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class BoardDao extends SqlSessionDaoSupport implements BoardDaoInter {

	@Override
	public int getTotalCount() {
		// TODO Auto-generated method stub
		int n=getSqlSession().selectOne("TotalCountOfBoard");
		return n;
	}

	@Override
	public void insertBoard(BoardDto dto) {
		// TODO Auto-generated method stub
		getSqlSession().insert("InsertOfBoard", dto);
	}

	@Override
	public List<BoardDto> getList(int start, int end) {

		Map<String, Integer>map=new HashMap<String, Integer>();
		map.put("start", start);
		map.put("end", end);
		
		return getSqlSession().selectList("selectpagingofboard",map);
	}

	@Override
	public void updateReadcount(int num) {
		getSqlSession().update("boardUpdateReadcount", num);
		
	}

	@Override
	public BoardDto getData(int num) {
		// TODO Auto-generated method stub
		return getSqlSession().selectOne("selectOneOfBoard", num);
	}

	@Override
	public void deleteBoard(int num) {
		// TODO Auto-generated method stub
		getSqlSession().delete("deleteOfBoard", num);
	}

	@Override
	public void updateBoard(BoardDto dto) {
		// TODO Auto-generated method stub
		getSqlSession().update("updateOfBoard", dto);
	}

}




 

boardList.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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<div class="alert alert-success">
	총<strong>${totalCount}</strong>개의 글이 있습니다
</div>

<div>
<button class="btn btn-danger btn-sm" style="font-size: 18px; width: 100px;" 
onclick="location.href='${path}/board/writeform'">글쓰기</button>
</div>

<table class="table table-bordered">
	<caption>게시판 목록</caption>
		<tr>
			<th style="width: 60px;">번호</th>
			<th style="width: 300px;">제목</th>
			<th style="width: 60px;">작성자</th>
			<th style="width: 60px;">조회</th>
			<th style="width: 120px;">작성일</th>
		</tr>
		<c:forEach var="dto" items="${list }">
		<tr>
			<td align="center">${no }</td>
			<c:set var="no" value="${no-1 }"/>
			<td>
			<a href="content?num=${dto.num }&pageNum=${currentPage}">${dto.subject }</a>
			</td>
			<td align="center">${dto.writer }</td>
			<td align="center">${dto.readcount }</td>
			<td align="center">
			<fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/>
			</td>
			
			
		</tr>
		</c:forEach>
</table>


<!-- 요기에 페이징 처리  -->

<div style="width:1000px; text-align: center;">
	<ul class="pagination">
		<c:if test="${startPage>1 }">
			<li>
				<a href="list?pageNum=${startPage-1 }">◀ </a>
			
			</li>		
		</c:if>
	
	<c:forEach var="pp" begin="${startPage }" end="${endPage }">
		<li>
			<c:if test="${pp==currentPage }">
				<a href="list?pageNum=${pp}" style="color: red;">${pp }</a>
			</c:if>
			<c:if test="${pp!=currentPage }">
				<a href="list?pageNum=${pp}" style="color: black;">${pp }</a>
			</c:if>
		
		</li>
	
	</c:forEach>
	
	<c:if test="${endPage<totalPage }">
			<li>
				<a href="list?pageNum=${endPage+1 }">▶ </a>
			
			</li>
		
		</c:if>

	</ul>
</div>


</body>

</html>

 

 

boardForm.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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<form action="write" method="post">
	<table class="table table-striped" style="width: 400px;">
		<caption>게시판 글쓰기</caption>
		<tr>
			<th>작성자</th>
			<td>
				<input type="text" name="writer" class="form-control">
			</td>
		</tr>
		
		<tr>
			<th>제목</th>
			<td>
				<input type="text" name="subject" class="form-control">
			</td>
		</tr>
		
		<tr>
			<td colspan="2">
				<textarea rows="10" cols="40" name="content"
				class="form-control">				
				</textarea>
			</td>
		</tr>
		
		<tr>			
			<td colspan="2" align="center">
				<button class="btn btn-default btn-lg">저장하기</button>
			</td>
		</tr>
		
	</table>
</form>
</body>
</html>

 

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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<table style="width: 500px;" class="table table-bordered">
	<tr>
		<th>
			${dto.subject }
			<span style="margin-left: 200px; color: gray;">
				<fmt:formatDate value="${dto.writeday }" pattern="yyyy-MM-dd HH:mm"/>
			</span>
		</th>
	</tr>
	<tr>
		<td>
		작성자: ${dto.writer }
			<span style="margin-left: 300px; color: gray">조회: ${dto.readcount }</span>
			<br>
			<pre><span>${dto.content }</span></pre>
		</td>	
	</tr>
</table>
<!-- 수정,삭제,목록 버튼들 -->

<div>
<button type="button" class="btn btn-info btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/list?pageNum=${pageNum }'">목록</button>

<button type="button" class="btn btn-danger btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/writeform?pageNum=${pageNum }'">글쓰기</button>

<button type="button" class="btn btn-success btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/updateform?num=${dto.num }&pageNum=${pageNum }'">수정</button>

<button type="button" class="btn btn-info btn-sm" style="width: 80px;"
onclick="location.href='${path}/board/delete?num=${dto.num }&pageNum=${pageNum }'">삭제</button>

</div>
</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
		BoardDaoInter dao;
	
		
		//게시판 출력
		@GetMapping ("/board/list") //메뉴에서 시작하니 매핑주소 맞출것
		public ModelAndView list(@RequestParam(value="pageNum",defaultValue="1")int currentPage)
		{
			ModelAndView model=new ModelAndView();
			int totalCount=dao.getTotalCount();
			//페이징처리에 필요한 변수
			int totalPage; //총 페이지 수
			int startNum; //각 페이지의 시작번호
			int endNum; //각 페이지의 끝번호
			int startPage; //블럭의 시작페이지
			int endPage; //블럭의 끝페이지
			int no; //출력할 시작번호
			int perPage=5; //한 페이지당 보여질 글의 갯수
			int perBlock=5; //한 페이지당 보여질 페이지의 갯수
			
			//총 페이지의 수를 구한다
			totalPage=totalCount/perPage+(totalCount%perPage>0?1:0);
			
			//존재하지 않는 페이지일 경우 마지막페이지로 가기
			if(currentPage>totalPage)
				currentPage=totalPage;
			
			//각 블럭의 시작페이지와 끝페이지 구하기
			//perBlock이 5일 경우
			//예: 한페이지가 3일 경우 시작페이지 1 끝 5
			//예: 한페이지가 7일 경우 시작페이지 6 끝 10
			//예: 한페이지가 11일 경우 시작페이지 11 끝 15
			
			startPage=(currentPage-1)/perBlock*perBlock+1;
			endPage=startPage+perBlock-1;
			//마지막블럭은 끝페이지가 총 페이지수와 같아야함
			if(endPage>totalPage)
				endPage=totalPage;
			
			//각 페이지의 시작번호와 끝 번호 구하기
			//perPage가 5일 경우
			//예: 1페이지: 시작번호:1  끝번호:5
			//예: 3페이지: 시작번호:1  끝번호:15
			startNum=(currentPage-1)*perPage+1;
			endNum=startNum+perPage-1;
			
			//마지막 페이지의 글번호 체크
			if(endNum>totalCount)
				endNum=totalCount;
			
			//각페이지마다 출력할 시작번호
			//총페이지가 30일 경우 1페이지는 30, 2페이지는 25.....
			no=totalCount-(currentPage-1)*perPage;
			
			//리스트 가져오기
			List<BoardDto>list=dao.getList(startNum, endNum);
			
			//페이징에 필요한 변수들 request로 저장...
			model.addObject("list", list);
			model.addObject("currentPage", currentPage);
			model.addObject("startPage", startPage);
			model.addObject("endPage", endPage);
			model.addObject("no", no);
			model.addObject("totalPage", totalPage);				
			model.addObject("totalCount", totalCount);
			model.setViewName("/board/boardList");
			
			return model;
		}
		
		//글쓰기 누르면 폼이 보이도록
		@GetMapping("/board/writeform")
		public String form()
		{
			return "/board/boardForm";
		}
		
		
		//폼에 글 입력후 저장되도록		
		@PostMapping("/board/write")
		public String readData(@ModelAttribute BoardDto dto)
		{
			dao.insertBoard(dto);
			return "redirect:list";
		}
		
		
		//제목 누르면 content 보기로
		@GetMapping("/board/content")
		public ModelAndView content(@RequestParam int num,
				@RequestParam int pageNum)
		{
			ModelAndView model=new ModelAndView();
			//조회 1증가
			dao.updateReadcount(num);
			//데이터 가져오기
			BoardDto dto=dao.getData(num);
			//모델에 저장
			model.addObject("dto", dto);
			model.addObject("pageNum", pageNum);
			model.setViewName("/board/content");
			
			return model;
		}
		
		
		@GetMapping("/board/delete")
		public String delete(@RequestParam int num, 
				@RequestParam String pageNum)
		{
			
			dao.deleteBoard(num);
			return "redirect:list?pageNum="+pageNum;
			
		}
		
		
		 @GetMapping("/board/updateform")
		 public ModelAndView updateform(@RequestParam int num, @RequestParam int pageNum) 
		 { 
			 ModelAndView model=new ModelAndView(); 
			 BoardDto dto=dao.getData(num); 
			 model.addObject("dto", dto);
			 model.addObject("pageNum", pageNum);
			 model.setViewName("/board/updateForm"); 
			 
			 return model;
		 
		 }
		 
		 @PostMapping("/board/update")
		 public String update(@ModelAttribute BoardDto dto, @RequestParam int pageNum)
		 {
			 dao.updateBoard(dto);
			 return "redirect:list?pageNum="+pageNum;
		 }
		
			
		 /*
			 * @GetMapping("/board/updateform") public String updateform() {
			 * 
			 * return "/board/updateForm"; }
			 */
		

	
}

 

updateForm.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>
<c:set var="path" value="<%=request.getContextPath() %>"></c:set>
<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>
<form action="update" method="post">
	<table class="table table-striped" style="width: 400px;">
		<caption>게시판 글쓰기</caption>
		<tr>
			<th>작성자</th>
			<td>
				<input type="text" name="writer" class="form-control" value="${dto.writer }">
			</td>
		</tr>
		
		<tr>
			<th>제목</th>
			<td>
				<input type="text" name="subject" class="form-control" value="${dto.subject }">
			</td>
		</tr>
		
		
		<tr>
			<td colspan="2">
				<textarea rows="10" cols="40" name="content"
				class="form-control">	
				${dto.content }			
				</textarea>
			</td>
		</tr>
		
		<tr>			
			<td colspan="2" align="center">
			<input type="hidden" name="num" value="${dto.num }" />
			<input type="hidden" name="pageNum" value="${pageNum }">
				<button class="btn btn-default btn-lg"
				type="submit">수정하기</button>
			</td>
		</tr>
		
	</table>
</form>
</body>
</html>

 

728x90
반응형

'IT일기(하반기) > SPRING' 카테고리의 다른 글

[spring] 게시판만들기 - 방명록편  (2) 2020.07.09
[spring] 로그인 만들어주기  (0) 2020.07.07
[spring] 제발 외우기  (0) 2020.07.07
[spring] 사이트 만들기  (0) 2020.07.06
[spring] 게시판 만들기 upload  (0) 2020.07.02