board_list
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@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>
<th>조회수</th>
</tr>
</thead>
<tbody>
<c:forEach var="vo" items="${list }" varStatus="num">
<tr>
<td>${num.count }</td>
<td>${vo.bno }</td>
<td>${vo.writer }</td>
<td><a href="board_content.board?bno=${vo.bno }" >${vo.title }</a></td>
<td><fmt:formatDate value="${vo.regdate }" pattern="yyyy-MM-dd HH시 mm분 ss초"/></td>
<td>${vo.hit }</td>
</tr>
</c:forEach>
</tbody>
<tbody>
<tr>
<td colspan="6" 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" %>
board_content
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%@include file="../include/header.jsp" %>
<div align="center" class="div_center">
<h3>게시글 내용 보기</h3>
<hr>
<table border="1" width="600">
<tr>
<td width="20%">글번호</td>
<td width="30%">${vo.bno }</td>
<td width="20%">조회수</td>
<td width="30%">${vo.hit }</td>
</tr>
<tr>
<td>작성자</td>
<td>${vo.writer }</td>
<td>작성일</td>
<td ><fmt:formatDate value="${vo.regdate }" pattern="yyyy-MM-dd HH시 mm분 ss초"/></td>
</tr>
<tr>
<td width="20%">글제목</td>
<td colspan="3">${vo.title }</td>
</tr>
<tr>
<td width="20%">글내용</td>
<td colspan="3" height="120px">${vo.content }</td>
</tr>
<tr>
<td colspan="4" align="center">
<input type="button" value="목록" onclick="location.href='board_list.board'">
<c:if test="${sessionScope.user_id != null }">
<input type="button" value="수정" onclick="location.href='board_modify.board?bno=${vo.bno}&writer=${vo.writer }' ">
<input type="button" value="삭제" onclick="location.href='board_delete.board?bno=${vo.bno}&writer=${vo.writer }'">
</c:if>
</td>
</tr>
</table>
</div>
<%@include file="../include/footer.jsp" %>
content페이지에서 수정페이지로 넘어갈 때
프로세스 생각...
삭제는 get방식으로 만들면 안된다. ->url주소 쳐서 삭제해버릴 수 있기 때문!
근데 그걸 알려면 JS를 알아야 한다..
지금은 그냥 get으로.
table묶어서 submit으로도 하려면 할 수 있다
board_modify
<%@ 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="updateForm.board" method="post">
<table border="1" width="500">
<%--
화면에 보일 필요는 없는데, 데이터를 보내야 하는 경우 hidden태그를 사용합니다.
--%>
<tr>
<td>글 번호</td>
<td>${vo.bno }<input type="hidden" name="bno" value="${vo.bno }"></td>
</tr>
<tr>
<td>작성자</td>
<td><input type="text" name="writer" value="${vo.writer }" readonly></td>
</tr>
<tr>
<td>글 제목</td>
<td>
<input type="text" name="title" value="${vo.title }">
</td>
</tr>
<tr>
<td>글 내용</td>
<td>
<textarea rows="10" style="width: 95%;" name="content">${vo.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" %>
수정파일
textarea태그는 value속성이 없고 태그사이에 값을 넣으면 된다 -> ${ }사용
글번호에 input이 없다. 따라서 bno는 넘어가지 않는다(사실 수정화면에는 글번호를 찍을 일도 없다).
그런데, 글번호 값은 넘겨줘야 함. 그래서 input태그에 type="hidden"으로 화면에 보이지 않지만 있도록.
=>hidden-화면에 보일 필요는 없는데 반드시 데이터를 보내줘야 할 때 사용. 개발자도구를 쓰면 보인다
삭제는 controller-service-DAO에서.
BoardController
package com.example.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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.model.BoardVO;
import com.example.board.service.BoardService;
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());
BoardService service=new BoardServiceImpl();
HttpSession session=request.getSession();
if(command.equals("/board/board_write.board")) { //등록화면
request.getRequestDispatcher("board_write.jsp").forward(request, response);
}else if(command.equals("/board/board_list.board")) { //목록화면
//조회메서드 -
ArrayList<BoardVO> list = service.getList(request, response);
request.setAttribute("list",list);
request.getRequestDispatcher("board_list.jsp").forward(request, response);
}else if(command.equals("/board/board_content.board")) { //상세내용화면
//조회한 글에 대한 정보 조회
BoardVO vo = service.getContent(request, response);
request.setAttribute("vo", vo);
request.getRequestDispatcher("board_content.jsp").forward(request, response);
}else if(command.equals("/board/board_modify.board")) { //수정화면
//조회한 글에 대한 정보 조회 재활용!! 어차피 똑같은 내용
BoardVO vo = service.getContent(request, response);
request.setAttribute("vo", vo);
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");
}else if(command.equals("/board/updateForm.board")) {
service.update(request, response);
//1st
//response.sendRedirect("board_list.board");
//2nd
//값을 보여주기 위해서는 키값을 통해 content에서 보여줘야 하는데, bno를 가져와서 넣어줘야 한다
//get방식으로 값을 넣어서 보내준다.
response.sendRedirect("board_content.board?bno="+request.getParameter("bno"));
}else if(command.equals("/board/board_delete.board")){
int result = service.delete(request, response);
String msg="";
if(result==1) {
msg="삭제성공";
}else {
msg="삭제실패";
}
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<script>");
out.println("alert('"+msg+"');");
out.println("location.href='board_list.board';");
out.println("</script>");
}
}
}
메세지출력을 out객체로 하고 있는데, 나중에 다른 방법도 배운다.
BoardService
package com.example.board.service;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.board.model.BoardVO;
public interface BoardService {
public void regist(HttpServletRequest request, HttpServletResponse response);//등록
ArrayList<BoardVO> getList(HttpServletRequest request, HttpServletResponse response);//조회
//public 생략해도 public. vo는 한 행만 가져오겠다는 뜻. list에 vo를 담아서 가져와야 한다
public BoardVO getContent(HttpServletRequest request, HttpServletResponse response);
void update(HttpServletRequest request, HttpServletResponse response);
int delete(HttpServletRequest request, HttpServletResponse response);
}
BoardServiceImpl
package com.example.board.service;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.board.model.BoardDAO;
import com.example.board.model.BoardVO;
public class BoardServiceImpl implements BoardService{
public void regist(HttpServletRequest request, HttpServletResponse response) {
String writer = request.getParameter("writer");
String title = request.getParameter("title");
String content = request.getParameter("content");
//DAO 메서드 호출
BoardDAO dao = BoardDAO.getInstance();
dao.regist(writer, title, content);
}
public ArrayList<BoardVO> getList(HttpServletRequest request, HttpServletResponse response) {
BoardDAO dao = BoardDAO.getInstance();
ArrayList<BoardVO> list = dao.getList();
return list;
}
public BoardVO getContent(HttpServletRequest request, HttpServletResponse response) {
//a태그로 넘어오는 param
String bno = request.getParameter("bno");
BoardDAO dao = BoardDAO.getInstance();
BoardVO vo = dao.getContent(bno);
//조회수 기능(중복방지 쿠키)
return vo;
}
public void update(HttpServletRequest request, HttpServletResponse response) {
//화면에서 넘어오는 값 writer는 안쓰니까 필요없다
String bno=request.getParameter("bno");
String title=request.getParameter("title");
String content=request.getParameter("content");
BoardDAO dao = BoardDAO.getInstance();
dao.update(bno, title, content);
}
public int delete(HttpServletRequest request, HttpServletResponse response) {
int result=0;
String bno=request.getParameter("bno");
BoardDAO dao = BoardDAO.getInstance();
result = dao.delete(bno);
return result;
}
}
BoardDAO
package com.example.board.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import com.example.util.JDBCUtil;
public class BoardDAO {
private static BoardDAO instance = new BoardDAO();
private BoardDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("드라이버클래스 로드에러");
}
}
public static BoardDAO getInstance() {
return instance;
}
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;
//메서드
public void regist(String writer, String title, String content) {
String sql="insert into board values(board_seq.nextval,?,?,?,sysdate,0)";
//String sql="insert into board(bno, writer, title, content, regdate, hit) 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();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
}
public ArrayList<BoardVO> getList() {
ArrayList<BoardVO> list = new ArrayList<>();
String sql="select * from board order by bno desc";//최신글 순서대로
try {
conn=DriverManager.getConnection(URL, UID, UPW);
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
//rs결과를 list에 저장
while(rs.next()) {
int bno2=Integer.parseInt(rs.getString("bno"));
String writer=rs.getString("writer");
String title=rs.getString("title");
String content = rs.getString("content");
Timestamp date = rs.getTimestamp("regdate");
int hit=Integer.parseInt(rs.getString("hit"));
BoardVO vo = new BoardVO(bno2, writer, title, content, date, hit);
list.add(vo);
//반복문 맨 처음에 vo를 기본생성자로 생성하고 vo.setBno(rs.getInt("bno")) 방식으로 돌려도 된다
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
return list;
}
public BoardVO getContent(String bno) {
BoardVO vo = null;
String sql="select * from board where bno=?";
try {
conn=DriverManager.getConnection(URL, UID, UPW);
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, bno);
rs=pstmt.executeQuery();
if(rs.next()) {
vo=new BoardVO();
vo.setBno(rs.getInt("bno"));
vo.setTitle(rs.getString("title"));
vo.setWriter(rs.getString("writer"));
vo.setContent(rs.getString("content"));
vo.setRegdate(rs.getTimestamp("regdate"));
vo.setHit(rs.getInt("hit"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
return vo;
}
public void update(String bno, String title, String content) {
String sql="update board set title=?, content=? where bno=?";
try {
conn=DriverManager.getConnection(URL, UID, UPW);
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, title);
pstmt.setString(2, content);
pstmt.setString(3, bno);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
}
public int delete(String bno) {
int result=0;
String sql="delete from board where bno=?";
try {
conn=DriverManager.getConnection(URL, UID, UPW);
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, bno);
result = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
JDBCUtil.close(conn, pstmt, rs);
}
return result;
}
}
'JSP' 카테고리의 다른 글
221207 Filter (0) | 2022.12.07 |
---|---|
221207 Board content와 modify (0) | 2022.12.07 |
221207 Board list출력 (0) | 2022.12.07 |
221206 Board 만들기 (0) | 2022.12.06 |
221206 회원정보(mypage), 회원정보수정, 회원탈퇴 만들기 (0) | 2022.12.06 |