반응형
우선 먼저 데이터 베이스의 테이블 생성을 한다.
또한 sequence를 주어 후에 primary key인 bno를 1씩 증가하게 설정해준다.
create table board(
bno number(10) primary key,
writer varchar2(30) not null,
title varchar2(50) not null,
content varchar2(500) ,
regdate date default sysdate,
hit number(10) default 0
);
create sequence board_seq nocache;
이 데이터를 담아줄 VO와 데이터 저장, 조회, 삭제, 업데이트를 해줄 DAO를 생성해준다.
package com.example.board.model;
import java.sql.Timestamp;
public class BoardVO {
private int bno;
private String writer;
private String title;
private String content;
private Timestamp regdate;
private int hit;
public BoardVO() {
// TODO Auto-generated constructor stub
}
public BoardVO(int bno, String writer, String title, String content, Timestamp regdate, int hit) {
super();
this.bno = bno;
this.writer = writer;
this.title = title;
this.content = content;
this.regdate = regdate;
this.hit = hit;
}
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getRegdate() {
return regdate;
}
public void setRegdate(Timestamp regdate) {
this.regdate = regdate;
}
public int getHit() {
return hit;
}
public void setHit(int hit) {
this.hit = hit;
}
}
package com.example.board.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.example.util.JDBCUtil;
public class BoardDAO {
//UserDAO 는 불필요하게 여러개 만들어질 필요가 없기 때문에
//하나의 객체만 만들어 지도록 Singleton형식으로 설계
//1. 나자신의 객체를 생성해서 1개로 제한
private static BoardDAO instance = new BoardDAO();
//2. 직접 객체를 생성 할 수 없도록 생성자에 private
private BoardDAO() {
//드라이버 클래스 로드
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("드라이버클래스 로드에러");
}
}
//3. 외부에서 객체 생성을 요구할 때 getter메서드를 통해 1번의 객체를 반환
public static BoardDAO getInstance() {
return instance;
}
//4.필요한 데이터 베이스 변수 선언
public String URL = "jdbc:oracle:thin:@localhost:1521:xe";
public String UID = "jsp";
public String UPW = "jsp";
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
//5.메서드
public void DAOregist(String writer, String title, String content){
String sql = "insert into board(bno, writer, title, content) values(board_seq.nextval,?,?,?)";
try {
conn = DriverManager.getConnection(URL,UID,UPW);
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, writer);
pstmt.setString(2, title);
pstmt.setString(3, content);
pstmt.executeUpdate();
//실행(성공시 1 실패시 0반환)
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
}
}
페이지를 생성하여 원하는 데이터를 입력할 수 있게 만들어 준다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@include file="../include/header.jsp"%>
<div class="container">
<h3>My Web게시판</h3>
<table class="table table-bordered">
<thead>
<tr>
<th>글 번호</th>
<th>작성자</th>
<th>제목</th>
<th>날짜</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="5" align="right">
<form action="" class="form-inline" >
<div class="form-group">
<input type="text" name="search" placeholder="제목검색" class="form-control" >
<input type="submit" value="검색" class="btn btn-default">
<input type="button" value="글 작성" class="btn btn-default" onclick="location.href='board_write.board'">
</div>
</form>
</td>
</tr>
</tbody>
</table>
</div>
<%@include file="../include/footer.jsp"%>
게시판 리스트 페이지 생성 글 작성을 누르면 아래와 같이 게시글 작성을 할 수 있는 페이지가 나오며 작성자, 제목, 내용을 적을 수 있는 input창이 생긴다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="../include/header.jsp"%>
<div align="center" class="div_center">
<h3>게시판 글 작성 페이지</h3>
<hr>
<form action="registForm.board" method="post">
<table border="1" width="500">
<tr>
<td>작성자</td>
<td>
<input type="text" name="writer" size="10" required>
</td>
</tr>
<tr>
<td>글 제목</td>
<td>
<input type="text" name="title" required>
</td>
</tr>
<tr>
<td>글 내용</td>
<td>
<textarea rows="10" style="width: 95%;" name="content"></textarea>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="작성 완료" >
<input type="button" value="목록" onclick="location.href='board_list.board'" >
</td>
</tr>
</table>
</form>
</div>
<%@include file="../include/footer.jsp"%>
원하는 내용을 입력하고 작성 완료를 누르면 controller를 통해서 service의 regist 메서드를 호출하고 service안에 regist 메서드 안에서 DAO regist메서드가 호출 되어 SQL에 저장이 된다.
package com.example.controller;
import java.io.IOException;
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 javax.servlet.http.HttpSession;
import com.example.board.service.BoardServiceImpl;
@WebServlet("*.board")
public class BoardController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request, response);
}
protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//한글 처리
request.setCharacterEncoding("utf-8");
//요청분기
String uri = request.getRequestURI();
String path = request.getContextPath();
String command = uri.substring(path.length());
System.out.println("요청경로:" + command);
HttpSession session;//자바에서 현재 세션 얻는 방법
BoardServiceImpl service = new BoardServiceImpl();
if(command.equals("/board/board_write.board")) {//등록화면
request.getRequestDispatcher("board_write.jsp").forward(request, response);
}else if(command.equals("/board/board_list.board")) {//목록화면
request.getRequestDispatcher("board_list.jsp").forward(request, response);
}else if(command.equals("/board/board_content.board")) {//상세내용화면
request.getRequestDispatcher("board_content.jsp").forward(request, response);
}else if(command.equals("/board/board_modify.board")) {//수정화면
request.getRequestDispatcher("board_modify.jsp").forward(request, response);
}else if(command.equals("/board/registForm.board")) {//글등록
/*
* 1. service의 regist메서드로 연결
* 2. service에서 등록에 필요한 파라미터를 받음
* 3. dao의 void regist메서드를 생성하고 insert작업
* 4. insert이후에 컨트롤러에서 리스트화면으로 리다이렉트
*/
service.regist(request, response);
response.sendRedirect("board_list.board");
}
}
}
package com.example.board.service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.board.model.BoardDAO;
public class BoardServiceImpl implements BoardService {
BoardDAO dao = BoardDAO.getInstance();
@Override
public void regist(HttpServletRequest request, HttpServletResponse response) {
String writer =request.getParameter("writer");
String title = request.getParameter("title");
String content = request.getParameter("content");
dao.regist(writer,title,content);
}
}
오늘은 리스트에 출력하지는 않고 SQL에 저장까지 해주고 마무리가 된다.
반응형
'통합' 카테고리의 다른 글
MVC2 게시글 수정하기 55일차 22.12.07 (0) | 2022.12.07 |
---|---|
MVC2 게시판 리스트 출력하기 55일차 22.12.07 (0) | 2022.12.07 |
MVC2 사용자 삭제 54일차-2 22.12.06 (0) | 2022.12.06 |
54일차-1 22.12.06 사용자 정보 수정 (0) | 2022.12.06 |
54일차-1 22.12.06 홈페이지 로그아웃 (0) | 2022.12.06 |
댓글