JSP 게시판

김성국·2023년 3월 16일
0
post-thumbnail
post-custom-banner

■ 실습) 게시판

dto)Board

package dto;
//2023.03.15
import java.util.Date;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString(exclude = {"regdate"})
@NoArgsConstructor
@AllArgsConstructor
public class Board {
	private long no;
	private String title;
	private String content;
	private String writer;
	private long hit;
	
	private Date regdate;
	

}

DB에서 데이터를 교환하기 위해서 DTO에 board 클레스를 생성한다.
즉, 데이터를 주고받을 수 있도록 설정된 객체를 담는 곳이다

BoardMapper

package mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;

import dto.Board;

public interface BoardMapper {
	@Insert({
		" INSERT INTO board(title, content, writer) ",
		" VALUES(#{obj.title},#{obj.content},#{obj.writer}) "
	})
	public int insertBoardOne(@Param("obj")Board obj);

}

Mapper는 MyBatis 매핑xml에 기재된 sql을 호출하기 위한 인터페이스이다.
BoardMapper를 통해 DTO에 Board 데이터를 주고 받을 수 있다.

■ 게시판글 등록(Controller)

package controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mapper.BoardMapper;

import java.io.IOException;

import config.MyBatisContext;
import dto.Board;

@WebServlet(urlPatterns = { "/board/insertone.do" })
public class BoardInsertServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);

	public BoardInsertServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// view로 정보를 전달
		request.setAttribute("title", "게시판글쓰기");

		// view를 표시.
		request.getRequestDispatcher("/WEB-INF/boardinsert1.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 사용자가 입력한 항목3개를 받아서 DB에 추가하고
		// 적절한 페이지로 이동시켜야함(절대로 post로 보내면 안됨, get으로만 보냄).
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		String writer = request.getParameter("writer");

		Board obj = new Board();
		obj.setTitle(title);
		obj.setContent(content);
		obj.setWriter(writer);

		int ret = bMapper.insertBoardOne(obj); // 4번
		if (ret == 1) { // 글쓰기 성공 => 게시판 목록 이동
			// 주소창을 selectlist.do로 변경시키고 엔터키를 누름 Get
			response.sendRedirect("selectlist.do");
		} else { // 글쓰기 실패 => 다시 글쓰기 화면으로 이동
					// 주소창을 insertone.do로 변경시키고 엔터키를 자동화 Get
			response.sendRedirect("insertone.do");

		}
	}

}

■ 게시판글 등록(boardinsert1)(View)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!-- jsp를 쓰기위한 import -->
<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>${title}</title>
	</head>
	<body>
		<h3>${title}</h3>
		<form action="insertone.do" method="post">
			제목 : <input type="text" name = "title" placeholder="제목입력"/> <br />
			내용 :<textarea rows="6" name = "content" placeholder="내용입력"/></textarea><br />
			작성자 : <input type="text" name = "writer" placeholder="작성자입력"><br />
			<input type="submit" value="글쓰기"/>
		</form>
	</body>
</html>


글쓰기 버튼을 누르면 DB에 데이터가 들어간다

  1. 사용자가 insertServlet으로 요청을 한다
  2. insertServlet이 View에 boardinsert1.jsp을 띄운다
  3. 화면 텍스트에 값을 입력하고 글쓰기 버튼을 누르면 boardinsert1.jsp ->insertServlet로 이동
  4. insertServlet에서 Mapper를 이용하여 DB에 데이터를 저장한다.

● 게시글 조회(10개씩 조회,page번호,1개씩 조회)

■ 10개씩 조회, 페이지 번호

■ boradSelectServlet(Controller)

package controller;

import java.io.IOException;
import java.util.List;

import config.MyBatisContext;
import dto.Board;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mapper.BoardMapper;

@WebServlet(urlPatterns = { "/board/selectlist.do" })
public class BoardSelectServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BoardSelectServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);

		int page = 1;
		if (request.getParameter("page") != null) {
			// get에는 ?page=1일 경우 1의 값을 읽는 방법
			page = Integer.parseInt(request.getParameter("page"));
		}

		// 1일경우 start 1 end 20
		// 2일경우 start 11 end 20
		// 3일경우 start 21 end 30

		// 1. mapper를 통해서 결과값 가져오기
		List<Board> list = bMapper.selectBoardList(10 * page - 9, 10 * page);
		long total = bMapper.countBoardList();

		// 2. view로 값전달
		request.setAttribute("pages", (total - 1) / 10 + 1);
		request.setAttribute("list", list);

		// 3. view로 표시
		request.getRequestDispatcher("/WEB-INF/boardselectlist1.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

■ BoardMapper(select)

■ boardselectlist1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<a href="insertone.do">글쓰기로 이동</a>
		<hr />
		
		<c:forEach var="obj" items="${list}">
			${obj.no}, <a href = "selectone.do?no=${obj.no}">${obj.title}</a>, ${obj.writer}, ${obj.hit},${obj.regdate}<br />
		</c:forEach>
		<hr />
		
		<c:forEach var="i" begin="1" end="${pages}">
			<a href="selectlist.do?page=${i}">${i}</a>
		</c:forEach>
		<!--  for(Board b : list)랑 같은 의미다 -->	
	</body>
</html>

■ 게시물 눌렀을때 1개씩 조회

■ BoardSelectOneServlet

package controller;

import java.io.IOException;

import config.MyBatisContext;
import dto.Board;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mapper.BoardMapper;

@WebServlet(urlPatterns = {"/board/selectone.do"})
public class BoardSelectOneServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BoardSelectOneServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);

		long no = Long.parseLong(request.getParameter("no"));
		
		// 1.mapper를 이용하여 게시글 1개 가져오기
		Board board = bMapper.selectBoardOne(no);
		
		// 2. View로 전송
		request.setAttribute("brd", board);
	
		// 3. view표시
		request.getRequestDispatcher("/WEB-INF/boardselectone1.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		}
	}

■ BoardMapper

■ boardseleclist1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<a href="insertone.do">글쓰기로 이동</a>
		<hr />
		
		<c:forEach var="obj" items="${list}">
			${obj.no}, <a href = "selectone.do?no=${obj.no}">${obj.title}</a>, ${obj.writer}, ${obj.hit},${obj.regdate}<br />
		</c:forEach>
		<hr />
		
		<c:forEach var="i" begin="1" end="${pages}">
			<a href="selectlist.do?page=${i}">${i}</a>
		</c:forEach>
		<!--  for(Board b : list)랑 같은 의미다 -->	
	</body>
</html>

■ 이전글, 다음글 이동

■ BoardSelectOneServlet

package controller;

import java.io.IOException;

import config.MyBatisContext;
import dto.Board;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mapper.BoardMapper;

@WebServlet(urlPatterns = {"/board/selectone.do"})
public class BoardSelectOneServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BoardSelectOneServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);

		long no = Long.parseLong(request.getParameter("no"));
		
		// 1.mapper를 이용하여 게시글 1개 가져오기
		Board board = bMapper.selectBoardOne(no);
		long next = bMapper.selectNextBoardOne(no);
		long prev = bMapper.selectPrevBoardOne(no);
		
		// 2. View로 전송
		request.setAttribute("brd", board);
		request.setAttribute("next", next);
		request.setAttribute("prev", prev);
	
		// 3. view표시
		request.getRequestDispatcher("/WEB-INF/boardselectone1.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		}
	}

■ boardMapper

■ boardselectOne1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>게시글조회</title>
</head>
<body>
	<h3>게시글조회</h3>
	<hr />
	글번호 : ${brd.no}
	<br /> 글제목 : ${brd.title}
	<br /> 글내용 : ${brd.content}
	<br /> 작성자 : ${brd.writer}
	<br /> 조회수 : ${brd.hit}
	<br /> 날짜 : ${brd.regdate}
	<br />

	<hr />
	<a href="selectlist.do"><input type="button" value="목록" /></a>
	<input type="button" value="수정" />

	<form action="deleteone.do" method="post"
		style="display: inline-block;">
		<input type="text" name="no" value="${brd.no}" /> <input type="submit"
			value="삭제" />
	</form>

	<c:if test="${peve > 0}">
	<a href="selectone.do?no=${prev}"><input type="button" value="이전글" /></a>
	</c:if>
	<c:if test="${next > 0}">
	<a href="selectone.do?no=${next}"> <input type="button" value="다음글" /></a>
	</c:if>
</body>
</html>

■ 수정

■ boardselectOne1.jsp

package controller;

import java.io.IOException;

import config.MyBatisContext;
import dto.Board;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import mapper.BoardMapper;

@WebServlet(urlPatterns = { "/board/updateone.do" })
public class BoardUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public BoardUpdateServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);
		// ?45
		long no = Long.parseLong(request.getParameter("no"));

		// mapper을 호출해서 결과값 받기
		Board board = bMapper.selectBoardOne(no);

		// view로 값 전달
		request.setAttribute("obj", board);

		request.getRequestDispatcher("/WEB-INF/boardupdateone1.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		BoardMapper bMapper = MyBatisContext.getSqlSession().getMapper(BoardMapper.class);
		// 전송되는 4개의 데이터를 받음
		long no = Long.parseLong(request.getParameter("no")); // view의 name값과 매칭
		String title = request.getParameter("title"); // view의 name값과 매칭
		String content = request.getParameter("content"); // view의 name값과 매칭
		String writer = request.getParameter("writer"); // view의 name값과 매칭

		// 여기는 데이터의 변경(추가, 수정, 삭제)를 수행하고
		Board b = new Board();
		b.setNo(no);
		b.setTitle(title);
		b.setContent(content);
		b.setWriter(writer);

		int ret = bMapper.updateBoardOne(b);
		// a태의 기능을 이용해서 페이지를 바꿈.
		if (ret == 1) {
			response.sendRedirect("selectone.do?no="+no);
		}else
			response.sendRedirect("updateone.do?no="+no);
	}
	// get(조회의기능), post(추가의기능), delete(삭제의기능), put(수정의기능), patch(일부의 수정 기능)
}

■ boardMapper

■ boardupdateone.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>게시글수정</title>
	</head>
	
	<body>
		<h3>게시글수정</h3>
		<form action="updateone.do" method="post">
			글번호 : <input type="text" value="${obj.no}" name="no" readonly /><br />
			글제목 : <input type="text" value="${obj.title}" name="title" /><br />
			글내용 : <textarea rows="6" name="content">${obj.content}</textarea><br />
			작성자 : <input type="text" value="${obj.writer}" name="writer" /><br />
			조회수 : <input type="text" value="${obj.hit}" readonly /><br />
			날짜 : <input type="text" value="${obj.regdate}" readonly /> <br />
			<input type="submit" value="게시글수정" />
			<a href="selectone.do?no=${obj.no}"><button>이전페이지이동</button></a>
		</form>
	</body>
</html>
post-custom-banner

0개의 댓글