Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 자동차수리시스템
- 예외미루기
- exception
- 집합_SET
- GRANT VIEW
- 자바
- 정수형타입
- EnhancedFor
- Java
- 인터페이스
- 환경설정
- 컬렉션프레임워크
- 사용자예외클래스생성
- 예외처리
- 한국건설관리시스템
- cursor문
- 참조형변수
- 오라클
- 어윈 사용법
- 컬렉션 타입
- oracle
- abstract
- 생성자오버로드
- 다형성
- 제네릭
- 메소드오버로딩
- 대덕인재개발원
- NestedFor
- 객체 비교
- 추상메서드
Archives
- Today
- Total
거니의 velog
231109_CRUD 과제 본문
1. DB 설정
create table board(
bo_no number(8) not null,
bo_title varchar2(150) not null,
bo_content varchar2(4000) not null,
bo_writer varchar2(150) not null,
bo_date date not null,
bo_hit number(8) not null,
CONSTRAINT pk_board PRIMARY KEY(bo_no)
);
commit;
select 'private ' ||
decode(lower(data_type), 'number', 'int ', 'String ') ||
lower(column_name) || ';'
from cols
where lower(table_name) = 'board';
create sequence board_seq
start with 1
increment by 1
nomaxvalue nocache;
select * from board;
2. MyBatis 준비
[dbinfo.properties]
# 이 줄은 주석 처리 줄 입니다...
# 이 문서의 작성 방법은
# 'key값=value값' 형식으로 작성한다.
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
user=test
pass=java
[mybatis-config.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!-- 이 문서는 mybatis의 환경 설정용 파일입니다. -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org/DTD config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="kr/or/ddit/mybatis/config/dbinfo.properties"/>
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>
<typeAliases>
<typeAlias type="kr.or.ddit.vo.BoardVO" alias="boardVo"/>
</typeAliases>
<environments default="oracleDevelopment">
<environment id="oracleDevelopment">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 연결 정보 설정하기 -->
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<property name="password" value="${pass}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="kr/or/ddit/mybatis/mappers/board-mapper.xml"/>
</mappers>
</configuration>
[board-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!-- 이 문서는 myBatis에서 처리할 SQL문을 작성하는 문서입니다. -->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="board">
<insert id="insertBoard" parameterType="boardVo">
INSERT INTO board (bo_no, bo_title, bo_content, bo_writer, bo_date, bo_hit)
VALUES (board_seq.nextval, #{bo_title}, #{bo_content}, #{bo_writer}, sysdate, 0)
</insert>
<update id="updateBoard" parameterType="boardVo">
UPDATE board
SET bo_title = #{bo_title}
, bo_content = #{bo_content}
, bo_writer = #{bo_writer}
, bo_date = sysdate
WHERE bo_no = #{bo_no}
</update>
<delete id="deleteBoard" parameterType="int">
DELETE
FROM board
WHERE bo_no = #{bo_no}
</delete>
<select id="getAllBoard" resultType="boardVo">
select * from board order by bo_no desc
</select>
<select id="getBoard" parameterType="int" resultType="boardVo">
select * from board where bo_no = #{bo_no}
</select>
<update id="hitUp" parameterType="boardVo">
UPDATE board
SET bo_hit = #{bo_hit}
WHERE bo_no = #{bo_no}
</update>
</mapper>
[MybatisUtil.java]
package kr.or.ddit.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
// myBatis 초기화 작업
Reader rd = null;
try {
rd = Resources.getResourceAsReader("kr/or/ddit/mybatis/config/mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(rd);
} catch (Exception e) {
System.out.println("myBatis 초기화 실패!!");
e.printStackTrace();
} finally {
if(rd!=null) try { rd.close(); }catch(IOException e) {}
}
}
// SqlSession객체를 반환하는 메서드 작성
public static SqlSession getSqlSession() {
SqlSession session = sqlSessionFactory.openSession();
return session;
}
}
3. VO, DAO, Service 클래스 만들기
[BoardVO.java]
package kr.or.ddit.vo;
public class BoardVO {
private int bo_no;
private String bo_title;
private String bo_content;
private String bo_writer;
private String bo_date;
private int bo_hit;
public BoardVO() {}
public BoardVO(int bo_no, String bo_title, String bo_content, String bo_writer, String bo_date, int bo_hit) {
this.bo_no = bo_no;
this.bo_title = bo_title;
this.bo_content = bo_content;
this.bo_writer = bo_writer;
this.bo_date = bo_date;
this.bo_hit = bo_hit;
}
public int getBo_no() {
return bo_no;
}
public void setBo_no(int bo_no) {
this.bo_no = bo_no;
}
public String getBo_title() {
return bo_title;
}
public void setBo_title(String bo_title) {
this.bo_title = bo_title;
}
public String getBo_content() {
return bo_content;
}
public void setBo_content(String bo_content) {
this.bo_content = bo_content;
}
public String getBo_writer() {
return bo_writer;
}
public void setBo_writer(String bo_writer) {
this.bo_writer = bo_writer;
}
public String getBo_date() {
return bo_date;
}
public void setBo_date(String bo_date) {
this.bo_date = bo_date;
}
public int getBo_hit() {
return bo_hit;
}
public void setBo_hit(int bo_hit) {
this.bo_hit = bo_hit;
}
@Override
public String toString() {
return "BoardVO [bo_no=" + bo_no + ", bo_title=" + bo_title + ", bo_content=" + bo_content + ", bo_writer="
+ bo_writer + ", bo_date=" + bo_date + ", bo_hit=" + bo_hit + "]";
}
}
[IBoardDAO.java]
package kr.or.ddit.board.dao;
import java.util.List;
import kr.or.ddit.vo.BoardVO;
public interface IBoardDAO {
/**
* 게시판 정보를 가져와 게시글을 등록하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int insertBoard(BoardVO bvo);
/**
* 게시판 정보를 가져와 게시글을 수정하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int updateBoard(BoardVO bvo);
/**
* 게시판 번호를 가져와 게시글을 삭제하는 기능
* @param boardNo
* @return 성공시 : 1, 실패시 : 0
*/
public int deleteBoard(int boardNo);
/**
* 게시판 전체 정보를 가져오는 기능
* @return List 타입에 게시글을 담은 VO 객체를 담아 리턴
*/
public List<BoardVO> getAllBoard();
/**
* 게시판 번호를 가져와 게시글 상세 정보를 보는 기능
* @param boardNo
* @return 게시글 정보 1건 리턴
*/
public BoardVO getBoard(int boardNo);
/**
* 게시판 상세 보기시 조회수가 1씩 증가하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int hitUp(BoardVO bvo);
}
[BoardDAOImpl.java]
package kr.or.ddit.board.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MybatisUtil;
import kr.or.ddit.vo.BoardVO;
public class BoardDAOImpl implements IBoardDAO {
// 싱글턴 패턴
private static BoardDAOImpl dao;
private BoardDAOImpl() {}
public static BoardDAOImpl getInstance() {
if(dao == null) dao = new BoardDAOImpl();
return dao;
}
@Override
public int insertBoard(BoardVO bvo) {
SqlSession session = MybatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.insert("board.insertBoard", bvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public int updateBoard(BoardVO bvo) {
SqlSession session = MybatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.update("board.updateBoard", bvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public int deleteBoard(int boardNo) {
SqlSession session = MybatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.delete("board.deleteBoard", boardNo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public List<BoardVO> getAllBoard() {
SqlSession session = MybatisUtil.getSqlSession();
List<BoardVO> boardList = null;
try {
boardList = session.selectList("board.getAllBoard");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return boardList;
}
@Override
public BoardVO getBoard(int boardNo) {
SqlSession session = MybatisUtil.getSqlSession();
BoardVO bvo = null;
try {
bvo = session.selectOne("board.getBoard", boardNo);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return bvo;
}
@Override
public int hitUp(BoardVO bvo) {
SqlSession session = MybatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.update("board.hitUp", bvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
}
[IBoardService.java]
package kr.or.ddit.board.service;
import java.util.List;
import kr.or.ddit.vo.BoardVO;
public interface IBoardService {
/**
* 게시판 정보를 가져와 게시글을 등록하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int insertBoard(BoardVO bvo);
/**
* 게시판 정보를 가져와 게시글을 수정하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int updateBoard(BoardVO bvo);
/**
* 게시판 번호를 가져와 게시글을 삭제하는 기능
* @param boardNo
* @return 성공시 : 1, 실패시 : 0
*/
public int deleteBoard(int boardNo);
/**
* 게시판 전체 정보를 가져오는 기능
* @return List 타입에 게시글을 담은 VO 객체를 담아 리턴
*/
public List<BoardVO> getAllBoard();
/**
* 게시판 번호를 가져와 게시글 상세 정보를 보는 기능
* @param boardNo
* @return 게시글 정보 1건 리턴
*/
public BoardVO getBoard(int boardNo);
/**
* 게시판 상세 보기시 조회수가 1씩 증가하는 기능
* @param bvo
* @return 성공시 : 1, 실패시 : 0
*/
public int hitUp(BoardVO bvo);
}
[BoardServiceImpl.java]
package kr.or.ddit.board.service;
import java.util.List;
import kr.or.ddit.board.dao.BoardDAOImpl;
import kr.or.ddit.board.dao.IBoardDAO;
import kr.or.ddit.vo.BoardVO;
public class BoardServiceImpl implements IBoardService {
private IBoardDAO dao;
private static BoardServiceImpl service;
private BoardServiceImpl() {
dao = BoardDAOImpl.getInstance();
}
public static BoardServiceImpl getInstance() {
if(service == null) service = new BoardServiceImpl();
return service;
}
@Override
public int insertBoard(BoardVO bvo) {
return dao.insertBoard(bvo);
}
@Override
public int updateBoard(BoardVO bvo) {
return dao.updateBoard(bvo);
}
@Override
public int deleteBoard(int boardNo) {
return dao.deleteBoard(boardNo);
}
@Override
public List<BoardVO> getAllBoard() {
return dao.getAllBoard();
}
@Override
public BoardVO getBoard(int boardNo) {
return dao.getBoard(boardNo);
}
@Override
public int hitUp(BoardVO bvo) {
return dao.hitUp(bvo);
}
}
4. CRUD 작업 시작
[web.xml]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>BoardWebProject</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
[index.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<jsp:forward page="/boardList.do"/>
[BoardList.java]
package kr.or.ddit.board.web;
import java.io.IOException;
import java.util.List;
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 kr.or.ddit.board.service.BoardServiceImpl;
import kr.or.ddit.board.service.IBoardService;
import kr.or.ddit.vo.BoardVO;
@WebServlet("/boardList.do")
public class BoardList extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
IBoardService service = BoardServiceImpl.getInstance();
List<BoardVO> boardList = service.getAllBoard();
request.setAttribute("boardList", boardList);
String jspPage = "/WEB-INF/views/board/boardList.jsp";
request.getRequestDispatcher(jspPage).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
[boardList.jsp]
<%@page import="kr.or.ddit.vo.BoardVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="author" content="이건정" />
<meta name="copyright" content="대덕인재개발원_306호" />
<title>게시판 CRUD 연습 > 게시판 목록</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
// 서블릿에서 보내온 자료 받기
List<BoardVO> boardList = (List<BoardVO>) request.getAttribute("boardList");
System.out.println("boardList : " + boardList);
%>
<c:set var="conPath" value="<%= request.getContextPath() %>"></c:set>
<c:set var="boardList" value="<%= boardList %>"></c:set>
<h1>게시판 목록</h1>
<br />
<hr />
<br />
<table border="1" style="width: 100%;">
<colgroup>
<col width="10%" />
<col width="40%" />
<col width="20%" />
<col width="20%" />
<col width="10%" />
</colgroup>
<tr>
<th>번호</th>
<th>제목</th>
<th>작성자</th>
<th>작성일</th>
<th>조회수</th>
</tr>
<c:choose>
<c:when test="${boardList ne null}">
<c:forEach var="boardVo" items="${boardList}">
<tr>
<td>${boardVo.getBo_no() }</td>
<td>
<a href="${conPath}/boardDetail.do?bno=${boardVo.getBo_no()}">${boardVo.getBo_title() }</a>
</td>
<td>${boardVo.getBo_writer() }</td>
<td>${boardVo.getBo_date() }</td>
<td>${boardVo.getBo_hit() }</td>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
<tr>
<td colspan="5">등록된 게시글이 없습니다.</td>
</tr>
</c:otherwise>
</c:choose>
<tr>
<td colspan="5">
<a href="${conPath}/boardInsert.do">게시글 등록</a>
</td>
</tr>
</table>
</body>
</html>
- http://localhost/
[BoardInsert.java]
package kr.or.ddit.board.web;
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 kr.or.ddit.board.service.BoardServiceImpl;
import kr.or.ddit.board.service.IBoardService;
import kr.or.ddit.vo.BoardVO;
@WebServlet("/boardInsert.do")
public class BoardInsert extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("게시글 등록 페이지로 이동합니다잉?");
String jspPage = "/WEB-INF/views/board/boardInsert.jsp";
request.getRequestDispatcher(jspPage).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("게시글 등록 시작합니다잉?");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String title = request.getParameter("title");
String content = request.getParameter("content");
String writer = request.getParameter("writer");
//System.out.println("title : " + title);
//System.out.println("content : " + content);
//System.out.println("writer : " + writer);
BoardVO bvo = new BoardVO();
bvo.setBo_title(title);
bvo.setBo_content(content);
bvo.setBo_writer(writer);
IBoardService service = BoardServiceImpl.getInstance();
int insCnt = service.insertBoard(bvo);
if(insCnt > 0) { // 게시글 등록 성공! 성공하면 바로 화면 이동임
response.sendRedirect(request.getContextPath() + "/boardList.do");
}else { // 게시글 등록 실패~ 넘겨줄 파라미터 값은 없음~
response.sendRedirect(request.getContextPath() + "/boardInsert.do");
}
}
}
[boardInsert.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="author" content="이건정" />
<meta name="copyright" content="대덕인재개발원_306호" />
<title>게시판 CRUD 연습 > 게시판 등록</title>
</head>
<body>
<c:set var="conPath" value="<%= request.getContextPath() %>"></c:set>
<h1>게시판 등록</h1>
<br />
<hr />
<br />
<form action="${conPath}/boardInsert.do" method="post">
<table border="1" style="width: 100%;">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tr>
<th>제목</th>
<td>
<input type="text" name="title" style="width: 95%;" />
</td>
</tr>
<tr>
<th>내용</th>
<td>
<textarea name="content" style="width: 95%; height: 100px;" wrap="soft"></textarea>
</td>
</tr>
<tr>
<th>작성자</th>
<td>
<input type="text" name="writer" style="width: 95%;" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">글 등록하기</button>
<a href="${conPath}/">게시판 목록으로 가기</a>
</td>
</tr>
</table>
</form>
</body>
</html>
- http://localhost/boardInsert.do
[BoardDetail.java]
package kr.or.ddit.board.web;
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 kr.or.ddit.board.service.BoardServiceImpl;
import kr.or.ddit.board.service.IBoardService;
import kr.or.ddit.vo.BoardVO;
@WebServlet("/boardDetail.do")
public class BoardDetail extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String bno = request.getParameter("bno");
//System.out.println("bno : " + bno);
int ibno = Integer.parseInt(bno);
// 게시판 상세 정보 가져오기
IBoardService service = BoardServiceImpl.getInstance();
BoardVO bvo = service.getBoard(ibno);
// 게시판 조회수 1 증가
int hit = bvo.getBo_hit();
hit++;
BoardVO hitVo = new BoardVO();
hitVo.setBo_no(ibno);
hitVo.setBo_hit(hit);
int updCnt = service.hitUp(hitVo);
if(updCnt > 0) { // 조회수 증가 성공
System.out.println("해당 글의 조회수가 1 증가하였습니다...");
}
request.setAttribute("bvo", bvo);
String jspPage = "/WEB-INF/views/board/boardDetail.jsp";
request.getRequestDispatcher(jspPage).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
[boardDetail.jsp]
<%@page import="kr.or.ddit.vo.BoardVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="author" content="이건정" />
<meta name="copyright" content="대덕인재개발원_306호" />
<title>게시판 CRUD 연습 > 게시판 상세보기</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
BoardVO bvo = (BoardVO) request.getAttribute("bvo");
System.out.println("bvo : " + bvo);
%>
<c:set var="conPath" value="<%= request.getContextPath() %>"></c:set>
<c:set var="bvo" value="<%= bvo %>"></c:set>
<h1>게시판 상세보기</h1>
<br />
<hr />
<br />
<table border="1" style="width: 100%;">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tr>
<th>제목</th>
<td>${bvo.getBo_title()}</td>
</tr>
<tr>
<th>내용</th>
<td>
<p style="white-space: pre-wrap">${bvo.getBo_content()}</p>
</td>
</tr>
<tr>
<th>작성자</th>
<td>${bvo.getBo_writer()}</td>
</tr>
<tr>
<th>작성일</th>
<td>${bvo.getBo_date()}</td>
</tr>
<tr>
<td colspan="2">
<a href="${conPath}/boardModify.do?bno=${bvo.getBo_no()}">수정</a>
<a href="${conPath}/boardDelete.do?bno=${bvo.getBo_no()}">삭제</a>
<a href="${conPath}/">게시판 목록으로 가기</a>
</td>
</tr>
</table>
</body>
</html>
- http://localhost/boardDetail.do?bno=7
[BoardDelete.java]
package kr.or.ddit.board.web;
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 kr.or.ddit.board.service.BoardServiceImpl;
import kr.or.ddit.board.service.IBoardService;
@WebServlet("/boardDelete.do")
public class BoardDelete extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String bno = request.getParameter("bno");
System.out.println("bno : " + bno);
int ibno = Integer.parseInt(bno);
IBoardService service = BoardServiceImpl.getInstance();
int delCnt = service.deleteBoard(ibno);
if(delCnt > 0) { // 게시글 삭제 성공! 성공하면 넘길 파라미터 없이 바로 화면 이동!
response.sendRedirect(request.getContextPath() + "/boardList.do");
}else { // 게시글 삭제 실패~ 이 때는 이전 화면으로 돌아가야 하는데 수정 화면에서 해당 게시글 번호가 있어야 데이터를 불러오니까 bno 넘김.
response.sendRedirect(request.getContextPath() + "/boardDetail.do?bno=" + bno);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
- http://localhost/boardDetail.do?bno=7
[boardModify.java]
package kr.or.ddit.board.web;
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 kr.or.ddit.board.service.BoardServiceImpl;
import kr.or.ddit.board.service.IBoardService;
import kr.or.ddit.vo.BoardVO;
@WebServlet("/boardModify.do")
public class BoardModify extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("게시글 수정 페이지로 이동합니다잉?");
request.setCharacterEncoding("utf-8");
String bno = request.getParameter("bno");
int ibno = Integer.parseInt(bno);
IBoardService service = BoardServiceImpl.getInstance();
BoardVO bvo = service.getBoard(ibno);
request.setAttribute("bvo", bvo);
String jspPage = "/WEB-INF/views/board/boardModify.jsp";
request.getRequestDispatcher(jspPage).forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("게시글 수정 시작합니다잉?");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String title = request.getParameter("title");
String content = request.getParameter("content");
String writer = request.getParameter("writer");
String bno = request.getParameter("bno");
int ibno = Integer.parseInt(bno);
System.out.println("title : " + title);
System.out.println("content : " + content);
System.out.println("writer : " + writer);
System.out.println("bno : " + bno);
BoardVO bvo = new BoardVO();
bvo.setBo_no(ibno);
bvo.setBo_title(title);
bvo.setBo_content(content);
bvo.setBo_writer(writer);
IBoardService service = BoardServiceImpl.getInstance();
int updCnt = service.updateBoard(bvo);
if(updCnt > 0) { // 게시글 수정 성공! 수정 이후에는 게시글 상세보기 페이지로 이동해야 하는데 해당 게시판 번호가 있어야 조회가 가능~
response.sendRedirect(request.getContextPath() + "/boardDetail.do?bno=" + bno);
}else { // 게시글 등록 실패~ 실패 이후에 이전의 수정 화면으로 넘어가는데 이 때도 해당 게시판 번호가 있어야 값이 넣어진 상태로 시작됨~
response.sendRedirect(request.getContextPath() + "/boardModify.do?bno=" + bno);
}
}
}
[boardModify.jsp]
<%@page import="kr.or.ddit.vo.BoardVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="author" content="이건정" />
<meta name="copyright" content="대덕인재개발원_306호" />
<title>게시판 CRUD 연습 > 게시판 수정</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
BoardVO bvo = (BoardVO) request.getAttribute("bvo");
System.out.println("bvo : " + bvo);
%>
<c:set var="conPath" value="<%= request.getContextPath() %>"></c:set>
<c:set var="bvo" value="<%= bvo %>"></c:set>
<h1>게시판 수정</h1>
<br />
<hr />
<br />
<form action="${conPath}/boardModify.do?bno=${bvo.getBo_no()}" method="post">
<table border="1" style="width: 100%;">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<tr>
<th>제목</th>
<td>
<input type="text" name="title" style="width: 95%;" value="${bvo.getBo_title()}" />
</td>
</tr>
<tr>
<th>내용</th>
<td>
<textarea name="content" style="width: 95%; height: 100px;" wrap="soft">${bvo.getBo_content()}</textarea>
</td>
</tr>
<tr>
<th>작성자</th>
<td>
<input type="text" name="writer" style="width: 95%;" value="${bvo.getBo_writer()}" />
</td>
</tr>
<tr>
<td colspan="2">
<button type="submit">글 수정하기</button>
<a href="${conPath}/">게시판 목록으로 가기</a>
</td>
</tr>
</table>
</form>
</body>
</html>
- http://localhost/boardModify.do?bno=6
'대덕인재개발원 > 대덕인재개발원_웹기반 애플리케이션' 카테고리의 다른 글
231113_JSP 개론 13 (0) | 2023.11.13 |
---|---|
231110_JSP 개론 12 (0) | 2023.11.10 |
231109_JSP 개론 11 (0) | 2023.11.09 |
231108_JSP 개론 10 (0) | 2023.11.08 |
231107_JSP 과제 5 (0) | 2023.11.07 |