오늘이라도

[MyBatis] 19. 게시판 만들기 ② : 게시글 작성 본문

취업성공패키지 SW 개발자 교육/Web

[MyBatis] 19. 게시판 만들기 ② : 게시글 작성

upcake_ 2020. 6. 3. 10:59
반응형

https://github.com/upcake/Class_Examples

교육 중에 작성한 예제들은 깃허브에 올려두고 있습니다. 

gif 파일은 클릭해서 보는 것이 정확합니다.


 - 게시판 만들기 ② : 게시글 작성 -

□ 진행 상황(※ 볼드체 : 오늘 다룬 파일들)

 JAVA

- com.hanul.mybatis : board.sql, db.properties, SqlMapConfig.xml, boardMapper.xml

- com.hanul.dto : BoardDTO.java, SearchDTO.java

- com.hanul.dao : BoardDAO.java

- com.hanul.controller : BoardFrontController.java  Servlet : web.xml에서 Mapping

- com.hanul.action : Action.java(Interface), ActionForward.java,

                           Boardxxx.java(BoardListAction.java, BoardInsertAction.java, BoardDetailAction.java)

-----------------------------------------------------------------------------------------------------

 WebContent

- boardMain.html

- board\ : *.jsp (boardList.jsp, boardInsertForm.jsp, boardDetail.jsp)

- css\ : *.css

- js\ : *.js

- images\ : *.png, *.gif, *.jpg

-----------------------------------------------------------------------------------------------------

○ 목록 조회

boardMain.html  boardList.do(*.do)  web.xml  BoardFrontController.java(Servlet)

 BoardListAction.java  BoardDAO.java  boardMapper.xml  BoardDAO.java

 BoardListAction.java  BoardFrontController.java  ActionForward.java

 boardList.jsp

-----------------------------------------------------------------------------------------------------

○ 게시글 작성

boardList.jsp boardInsertForm.do(*.do) web.xml BoardFrontController.java(Servlet)

boardInsertForm.jsp(입력화면) boardInsert.do(*.do) web.xml

BoardFrontController.java(Servlet) BoardInsertAction.java BoardDAO.java

boardMapper.xml BoardDAO.java BoardInsertAction.java

BoardFrontController.java ActionForward.java boardList.do

-----------------------------------------------------------------------------------------------------

 

□ 작동 화면 및 코드

 

▼boardMapper.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="com.hanul.mybatis.boardMapper.xml">
	<select id="boardSearchAll" resultType="BoardDTO">
		SELECT * FROM tblBoard ORDER BY b_num DESC
	</select>
	
	<insert id="boardInsert" parameterType="BoardDTO">
		INSERT INTO tblBoard
		VALUES(b_num_seq.NEXTVAL,
				#{b_subject },
				#{b_pwd },
				#{b_content },
				#{b_writer},
				SYSDATE,
				0)
	</insert>
</mapper>

 

▼BoardDTO.java

package com.hanul.dto;

import java.io.Serializable;

public class BoardDTO implements Serializable {
	private int b_num;
	private String b_subject;
	private String b_pwd;
	private String b_content;
	private String b_writer;
	private String b_date;
	private int b_readcount;
	
	public BoardDTO() {}

	
	
	public BoardDTO(String b_subject, String b_pwd, String b_content, String b_writer) {
		super();
		this.b_subject = b_subject;
		this.b_pwd = b_pwd;
		this.b_content = b_content;
		this.b_writer = b_writer;
	}



	public BoardDTO(int b_num, String b_subject, String b_pwd, String b_content, String b_writer, String b_date,
			int b_readcount) {
		super();
		this.b_num = b_num;
		this.b_subject = b_subject;
		this.b_pwd = b_pwd;
		this.b_content = b_content;
		this.b_writer = b_writer;
		this.b_date = b_date;
		this.b_readcount = b_readcount;
	}

	public int getB_num() {
		return b_num;
	}

	public void setB_num(int b_num) {
		this.b_num = b_num;
	}

	public String getB_subject() {
		return b_subject;
	}

	public void setB_subject(String b_subject) {
		this.b_subject = b_subject;
	}

	public String getB_pwd() {
		return b_pwd;
	}

	public void setB_pwd(String b_pwd) {
		this.b_pwd = b_pwd;
	}

	public String getB_content() {
		return b_content;
	}

	public void setB_content(String b_content) {
		this.b_content = b_content;
	}

	public String getB_writer() {
		return b_writer;
	}

	public void setB_writer(String b_writer) {
		this.b_writer = b_writer;
	}

	public String getB_date() {
		return b_date;
	}

	public void setB_date(String b_date) {
		this.b_date = b_date;
	}

	public int getB_readcount() {
		return b_readcount;
	}

	public void setB_readcount(int b_readcount) {
		this.b_readcount = b_readcount;
	}
	
	
	
}

 

▼BoardDAO.java

package com.hanul.dao;

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

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.hanul.dto.BoardDTO;

public class BoardDAO {
	//①SqlSessionFactory 설정
	private static SqlSessionFactory sqlMapper;
	static {
		String resource = "com/hanul/mybatis/SqlMapConfig.xml";
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlMapper = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("SqlSessionFactory Exception");
		}
	} //static
	
	//전체 목록 검색
	public List<BoardDTO> boardSearchAll() {
		SqlSession session = sqlMapper.openSession();
		List<BoardDTO> list = null;
		list = session.selectList("boardSearchAll");
		session.close();
		return list;
	} //boardSearchAll()
	
	//작성한 글 등록
	public int boardInsert(BoardDTO dto) {
		SqlSession session = sqlMapper.openSession();
		//alert 창을 사용할 경우에는 succ를 return 해야한다.
		//PrintWriter 이용한 script 코드로 구현한 후 처리
		int succ = 0;
		succ = session.insert("boardInsert", dto);
		session.commit();
		session.close();
		return succ;
	} //boardInsert()
} //class

 

▼BoardFrontController.java

package com.hanul.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanul.action.Action;
import com.hanul.action.ActionForward;
import com.hanul.action.BoardDetailAction;
import com.hanul.action.BoardInsertAction;
import com.hanul.action.BoardListAction;

@WebServlet("/BoardFrontController.do")
public class BoardFrontController extends HttpServlet {
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//0. 불필요한 코드를 지우고 서비스 메서드만 남겨둔다.
		//1. 클라이언트가 어떤 요청을 했는지를 파악한다.
		request.setCharacterEncoding("utf-8");
		//localhost:8080/mbb/boardList.do
		//mbb : context root
		//mbb/boardList.do : uri-pattern
		//uri-pattern에서 context root를 잘라내서 boardList.do만 남긴다.
		String uri = request.getRequestURI();		//uri-pattern 값	: /mbb/XXX.do
		String ctx = request.getContextPath();		//Context root 값	: /mbb
		String command = uri.substring(ctx.length());	//실제 요청한 페이지 : /XXX.do
		//System.out.println("uri : " + uri);
		//System.out.println("ctx : " + ctx);
		//System.out.println("command : " + command);
		
		
		//2. 클라이언트의 요청(*.do → command)과 실제 처리할 비즈니스 로직(Action Class) 연결
		Action action = null;
		ActionForward forward = null;
		
		if(command.equals("/boardList.do")) {
			action = new BoardListAction();		//상위 객체(부모)쪽으로 업캐스팅 (다형성)
			forward = action.execute(request, response);
		} else if(command.equals("/boardInsertForm.do")) {	//글쓰기 폼으로 화면 전환만 필요 (Action 클래스 필요 X, 화면 전환은 ActionForward가 담당)
			forward = new ActionForward();
			forward.setPath("board/boardInsertForm.jsp");
			forward.setRedirect(false);
		} else if(command.equals("/boardInsert.do")) {
			action = new BoardInsertAction();
			forward = action.execute(request, response); //forward에 null값이 리턴된다.
		}
		
		//3. 페이지 전환(프레젠테이션 로직) : sendRedirect(), forward()
		if(forward != null) {	//forward가 null 아니면 작동
			if(forward.isRedirect()) {	//true : sendRedirect() 페이지 전환
				response.sendRedirect(forward.getPath());
			} else {					//false : forward() 페이지 전환
				RequestDispatcher rd = request.getRequestDispatcher(forward.getPath());
				rd.forward(request, response);
			}	
		}
	}
}

 

▼boardList.jsp

<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@page import="com.hanul.dto.BoardDTO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
request.setCharacterEncoding("utf-8");
List<BoardDTO> list = (List<BoardDTO>)request.getAttribute("list");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BoardList JSP</title>
</head>
<body>
<div align="center">
	<h3>[게시판 전체 목록 보기]</h3>
	<table border="1">
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성자</th>
			<th>작성일</th>
			<th>조회수</th>
		</tr>
		
		<%--
		<!-- JSTL core 문법을 이용한 출력 : b_num_seq에 의해서 번호의 순서가 맞지 않다.-->
		<c:if test="${empty list }"> <!-- list.size()가 0이라면 -->
			<tr align="center">
				<td colspan="5">작성된 글이 없습니다.</td>
			</tr>
		</c:if>
		<c:if test="${list != null }">
			<c:forEach var="i" items="${list }">
				<tr align="center">
					<td>${i.b_num }</td>
					<td>${i.b_subject }</td>
					<td>${i.b_writer }</td>
					<td>${i.b_date }</td>
					<td>${i.b_readcount }</td>
				</tr>
			</c:forEach>
		</c:if>
		 --%>
		 
		 <!-- 향상된 for문을 이용한 출력 : 번호 순서가 맞지 않다 -->
		 <%--if(list.size() == 0) {
		 	out.println("<tr align='center'><td colspan='5'>작성된 글이 없습니다.</td></tr>");
		 } else {
			for(BoardDTO dto : list) {
				out.println("<tr align='center'>");
					out.println("<td>" + dto.getB_num() + "</td>");
					out.println("<td>" + dto.getB_subject() + "</td>");
					out.println("<td>" + dto.getB_writer() + "</td>");
					out.println("<td>" + dto.getB_date() + "</td>");
					out.println("<td>" + dto.getB_readcount() + "</td>");
				out.println("</tr>");
			}
		 }--%>
		 
		 <%
		 if(list.size() == 0) {
			 out.println("<tr align='center'><td colspan='5'>작성된 글이 없습니다.</td></tr>");
		 } else {
			 for(int i = 0; i < list.size(); i++) {
				 out.println("<tr align='center'>");
					//out.println("<td>" + list.get(i).getB_num() + "</td>");
					out.println("<td>" + (list.size() - i) + "</td>");
					out.println("<td>" + list.get(i).getB_subject() + "</td>");
					out.println("<td>" + list.get(i).getB_writer() + "</td>");
					out.println("<td>" + list.get(i).getB_date() + "</td>");
					out.println("<td>" + list.get(i).getB_readcount() + "</td>");
				out.println("</tr>");
			 }
		 }
		 %>
		 
		 <tr align="center">
		 	<td colspan="5">
		 		<input type="button" value="글쓰기" onclick="location.href='boardInsertForm.do'"/>
		 		<!-- boardInsertForm.do를 작성하지 않고 버튼을 누르면 404, 500에러가 나지 않고 빈 화면이 나온다.
		 		 BoardFrontController.java까지는 간 다음 서블렛에서 멈추기 때문 -->
		 	</td>
		 </tr>
	</table>
</div>
</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Board Insert Form</title>
<script type="text/javascript">
function fnSubmit() {
	if(confirm("작성하신 글을 등록하시겠습니까?")) {
		return true;
	}
	return false;
}

function fnReset() {
	if(confirm("입력하신 내용을 삭제하시겠습니까?")) {
		fnLoad();
		return true;
	}
	return false;
}

function fnLoad() {
	//폼에 name 속성을 줘서 폼 - 텍스트창으로 접근한다
	document.regForm.b_writer.focus();
}
</script>
</head>
<body onload="fnLoad()"><!-- 입력칸에 자동으로 포커스가 오게끔 설정 -->
<div align="center">
	<h3>[게시판 글쓰기]</h3>
	<form action="boardInsert.do" method="post" name="regForm" onsubmit="return fnSubmit()" onreset="return fnReset()">
		<table border="1">
			<tr>
				<th>작성자</th>
				<td><input type="text" name="b_writer" maxlength="20" required="required" /></td>
			</tr>
			<tr>
				<th>비밀번호</th>
				<td><input type="password" name="b_pwd" maxlength="20" required="required" />
			</tr>
			<tr>
				<th>제목</th>
				<td><input type="text" name="b_subject" maxlength="50" required="required" /></td>
			</tr>
			<tr>
				<th>내용</th>
				<td>
					<textarea rows="10" cols="50" name="b_content" required="required"></textarea>
				</td>
			</tr>
			<tr align="center">
				<td colspan="2">
					<input type="submit" value="등록" />
					<input type="reset" value="내용 삭제" />
					<input type="button" value="글 목록" onclick="location.href='boardList.do'" />
				</td>
			</tr>
		</table>
	</form>
</div>
</body>
</html>

 

▼BoardInsertAction.java

package com.hanul.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanul.dao.BoardDAO;
import com.hanul.dto.BoardDTO;

public class BoardInsertAction implements Action {
	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		//클라이언트의 요청을 받는다 : 매개 변수 정보를 가져온다 → DTO 묶어준다.
		request.setCharacterEncoding("utf-8");
		String b_writer = request.getParameter("b_writer");
		String b_subject = request.getParameter("b_subject");
		String b_content = request.getParameter("b_content");
		String b_pwd = request.getParameter("b_pwd");
		
		//입력하는 데이터의 개수가 DTO 생성자의 매개 변수보다 적을때,
		//데이터 입력 방법 ① : 기본 생성자 메서드 이용
		/*
		BoardDTO dto = new BoardDTO();
		dto.setB_writer(b_writer);
		//dto.setB_writer(request.getParameter("b_writer"));
		dto.setB_subject(b_subject);
		dto.setB_content(b_content);
		dto.setB_pwd(b_pwd);
		*/
		
		//데이터 입력 방법 ② : 입력할 데이터만 매개 변수로 받는 생성자를 DTO에 생성 (메서드 오버 로딩)
		BoardDTO dto = new BoardDTO(b_subject, b_pwd, b_content, b_writer);
		
		//비즈니스 로직 : DAO 연동(DB 접속, 쿼리 수행)
		BoardDAO dao = new BoardDAO();
		int succ = dao.boardInsert(dto);
		
		//프레젠테이션 로직 : alert 창을 사용 ▶ PrintWriter를 이용한 script 코드로 구현
		response.setContentType("text/html; charset = utf-8"); //MIME 설정
		PrintWriter out =response.getWriter(); 
		if(succ > 0) {
			out.println("<script> alert('등록 완료되었습니다.');");
			out.println("location.href = 'boardList.do';</script>");
		} else {
			out.println("<script> alert('등록 실패했습니다.');");
			out.println("location.href = 'boardList.do';</script>");
		}
		return null; 	//위의 코드(script)에서 페이지 전환이 이루어지므로,
						//ActionForward가 필요하지 않는다 → null을 리턴한다.
	}
}
반응형