일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 메모리스트림
- Linux셋팅
- char[] String 형변환
- 동기화
- 리눅스세팅
- 상관서브쿼리
- ObjectInputStream
- 스레드그룸
- sleep()메소드
- InputDialog
- interrupted()
- isinterrupted()
- include 지시자
- first-of-child
- ID중복
- include지시자
- 아이디중복
- include액션태그
- 리눅스셋팅
- MemoryStream
- Daemon()
- ThreadGroup()
- interrupt()
- first-child
- StringReader
- String char[] 형변환
- 표현 언어
- StringWriter
- Linux세팅
- 상관 서브 쿼리
- Today
- Total
다연이네
[days05] 게시판 만들기 본문
글목록을 클릭하면 목록 화면으로, 글쓰기를 클릭하면 글쓰기 화면으로 이동한다.
목록에서 위 아래의 글쓰기<- 글자를 입력해도 글쓰기 화면으로 이동한다.
글 작성한지 1시간이 지나지 않았다면 N아이콘이 제목 옆에 붙어있고, 작성자가 kenik이면 아이콘이 작성자명 옆에 붙어있다.
목록에서 글 제목을 클릭하면 각 글의 내용 화면으로 이동한다.
내용보기에서 하단 Home 버튼을 누르면 list 화면으로 이동하는데, 이때 검색 컨텐츠, 내용, 페이지 번호를 유지한다.
예시로 jsp를 검색한 후 7번 페이지의 특정 글 내용을 본 후 Home 버튼을 누르면 해당 페이지와 검색 내용이 유지되어 있다.
내용보기에서 하단의 삭제하기 버튼을 클릭하면 비밀번호를 입력하는 화면으로 이동한다.
비밀번호가 틀리면 알람을 띄운 후 다시 비밀번호 입력 화면으로 이동한다.
비밀번호가 일치하면 삭제된 채로 목록 화면으로 이동한다.
모달 창으로 삭제 버튼을 클릭하면 모달창으로 삭제가 된다.
하단 검색창을 통해 검색도 가능하다.
ex08.jsp
<%@ page 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>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
$(document).ready(function (){
});
</script>
</head>
<body>
<a href="/jspPro/cstvsboard/list.htm">글목록</a>
<a href="/jspPro/cstvsboard/write.htm">글쓰기</a>
<!-- days05.board패키지 > List.java 서블릿 등록 -->
</body>
</html>
BoardDTO.java
package days05.board;
import java.util.Date;
//VO ==DTO == 자바빈즈 (Java Bean) == POJO
public class BoardDTO {
private int seq ;
private String writer;
private String pwd;
private String email;
private String title;
private Date writedate ;
private int readed ;
private int tag;
private String content;
//default constructor
public BoardDTO() {
super();
}
//getter setter
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getWriter() {
return writer;
}
public void setWriter(String writer) {
this.writer = writer;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getWritedate() {
return writedate;
}
public void setWritedate(Date writedate) {
this.writedate = writedate;
}
public int getReaded() {
return readed;
}
public void setReaded(int readed) {
this.readed = readed;
}
public int getTag() {
return tag;
}
public void setTag(int tag) {
this.tag = tag;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
PageBlock.java
package days05.board;
public class PageBlock {
private int currentPage;
private int numberPerPage = 10;
private int numberOfPageBlock = 10;
private int start, end; // startOfPageBlock, endOfPageBlock;
private boolean prev, next;
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getNumberPerPage() {
return numberPerPage;
}
public void setNumberPerPage(int numberPerPage) {
this.numberPerPage = numberPerPage;
}
public int getNumberOfPageBlock() {
return numberOfPageBlock;
}
public void setNumberOfPageBlock(int numberOfPageBlock) {
this.numberOfPageBlock = numberOfPageBlock;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public boolean isPrev() {
return prev;
}
public void setPrev(boolean prev) {
this.prev = prev;
}
public boolean isNext() {
return next;
}
public void setNext(boolean next) {
this.next = next;
}
}
List.java - 목록과 관련된 서블릿
검색, 페이징 처리 모두 완료
package days05.board;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
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.util.DBConn;
/**
* Servlet implementation class List
*/
@WebServlet("/cstvsboard/list.htm")
public class List extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public List() {
super();
// TODO Auto-generated constructor stub
}
// 검색 X 페이징 처리 O
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("> List.java doGet()...");
// list.htm?currentPage=1&numberPerPage=10
// list.htm
String pCurrentPage = request.getParameter("currentPage");
int currentPage = pCurrentPage == null ? 1 : Integer.parseInt(pCurrentPage);
String pPumberPerPage = request.getParameter("numberPerPage");
int numberPerPage = pPumberPerPage == null ? 10 : Integer.parseInt(pPumberPerPage);
// 검색 추가 코딩
String pSearchCondition = request.getParameter("searchCondition");
int searchCondition = pSearchCondition == null ? 1 : Integer.parseInt(pSearchCondition);
String searchWord = request.getParameter("searchWord");
if( searchWord == null || searchWord == "") searchWord = "*";
//
request.setAttribute("searchWord", searchWord);
request.setAttribute("searchCondition", searchCondition);
Connection con = DBConn.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql =" SELECT * " +
" FROM ( " +
" SELECT rownum no, t.* " +
" FROM ( " +
" SELECT seq, title, writer, writedate, readed " +
" , case when ( sysdate - writedate) between 0 and 1/24 then 'true' else 'false' end newmark " +
" FROM TBL_CSTVSBOARD ";
switch (searchCondition) {
case 1: // 제목
sql += " WHERE regexp_like( title , ? , 'i' ) ";
break;
case 2: // 내용
sql += " WHERE regexp_like( content , ? , 'i' ) ";
break;
case 3: // 작성자
sql += " WHERE regexp_like( writer , ? , 'i' ) ";
break;
case 4: // 제목 + 내용
sql += " WHERE regexp_like( title , ? , 'i' ) OR regexp_like( content , ? , 'i' ) ";
break;
} // switch
sql += " ORDER BY seq DESC " +
" ) t " +
" ) b " +
" WHERE b.no BETWEEN ? AND ? ";
int start = (currentPage - 1)*numberPerPage+1;
int end = currentPage*numberPerPage;
ArrayList<BoardDTO> list = null;
try {
pstmt = con.prepareStatement(sql);
// BETWEEN ? AND ?
pstmt.setInt(1, start);
pstmt.setInt(2, end);
// 검색 조건 1/2/3/4
if (searchCondition == 4 ) {
// 검색조건 4 Wherer ? or ? Between ? And ?
pstmt.setString(1, searchWord);
pstmt.setString(2, searchWord);
pstmt.setInt(3, start);
pstmt.setInt(4, end);
} else {
pstmt.setString(1, searchWord);
pstmt.setInt(2, start);
pstmt.setInt(3, end);
}
rs = pstmt.executeQuery();
int seq;
String title;
String writer;
Date writedate; // java.sql.Date 타입.
int readed;
boolean newmark ;
BoardDTO dto = null;
if (rs.next()) {
list = new ArrayList<BoardDTO>();
do {
// 글번호 글제목 글쓴이 작성일 조회수
seq = rs.getInt("seq");
title = rs.getString("title");
if( searchCondition == 1 && !searchWord.equals("*")) {
title = title.replace(searchWord
, String.format("<span class=\"searchWord\">%s</span>", searchWord) );
}
writer = rs.getString("writer");
writedate = rs.getDate("writedate");
readed = rs.getInt("readed");
//newmark = rs.getBoolean("newmark"); //
newmark = Boolean.parseBoolean(rs.getString("newmark"));
dto = new BoardDTO();
dto.setSeq(seq);
dto.setTitle(title);
dto.setWriter(writer);
dto.setWritedate(writedate);
dto.setReaded(readed);
dto.setNewmark(newmark); //
list.add(dto);
} while (rs.next());
} // if
} catch (SQLException e1) {
e1.printStackTrace();
}finally {
try {
rs.close();
pstmt.close();
//DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try 현재 페이지 게시글 ArrayList 채워넣는 코딩
// *** 페이징 처리 시작~ ***
// 페이징 처리할 때 필요한 것을 필드로 가지는 클래스 선언 : PageBlock
// (ㄱ). 현재페이지 (ㄴ). 한페이지당 게시글수 ㄷ. 페이지블럭 ㄹ. 페이지블럭 시작, 끝 ㅁ. 이전, 다음
// 1. 총페이지수 계산
int totalPages = 0;
sql = "SELECT count(*) totalRecords , CEIL(count(*)/?) totalPages"
+" FROM TBL_CSTVSBOARD ";
switch (searchCondition) {
case 1: // 제목
sql += " WHERE regexp_like( title , ? , 'i' ) ";
break;
case 2: // 내용
sql += " WHERE regexp_like( content , ? , 'i' ) ";
break;
case 3: // 작성자
sql += " WHERE regexp_like( writer , ? , 'i' ) ";
break;
case 4: // 제목 + 내용
sql += " WHERE regexp_like( title , ? , 'i' ) OR regexp_like( content , ? , 'i' ) ";
break;
} // switch
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, numberPerPage);
pstmt.setString(2, searchWord);
if (searchCondition == 4 ) pstmt.setString(3, searchWord);
rs = pstmt.executeQuery();
if( rs.next() )
totalPages = rs.getInt("totalPages");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
rs.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try 총페이지 수 처리 블럭.
int numberOfPageBlock = 10;
int startOfPageBlock = (currentPage-1)/numberOfPageBlock*numberOfPageBlock+1;
int endOfPageBlock = startOfPageBlock + numberOfPageBlock -1;
if( endOfPageBlock > totalPages ) endOfPageBlock = totalPages;
// 2.
PageBlock pageBlock = new PageBlock();
pageBlock.setCurrentPage(currentPage);
//pageBlock.setNumberPerPage(numberPerPage);
//pageBlock.setNumberOfPageBlock(numberOfPageBlock);
pageBlock.setStart(startOfPageBlock);
pageBlock.setEnd(endOfPageBlock);
pageBlock.setPrev( startOfPageBlock != 1 ? true : false );
pageBlock.setNext( endOfPageBlock != totalPages ? true : false );
// 포워딩~
// ?currentPage=1&numberPerPage=10 list.jsp 파라미터 전달 O
request.setAttribute("list", list);
request.setAttribute("pageBlock", pageBlock);
String path = "/days05/board/list.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} // doGet
/** 검색 X, 페이징처리 X
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// System.out.println("> List.java doGet()...");
Connection con = DBConn.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT seq, title, writer, writedate, readed "
+ " FROM TBL_CSTVSBOARD "
+ " ORDER BY seq DESC";
ArrayList<BoardDTO> list = null;
try {
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
int seq;
String title;
String writer;
Date writedate; // java.sql.Date 타입.
int readed;
BoardDTO dto = null;
if (rs.next()) {
list = new ArrayList<BoardDTO>();
do {
// 글번호 글제목 글쓴이 작성일 조회수
seq = rs.getInt("seq");
title = rs.getString("title");
writer = rs.getString("writer");
writedate = rs.getDate("writedate");
readed = rs.getInt("readed");
dto = new BoardDTO();
dto.setSeq(seq);
dto.setTitle(title);
dto.setWriter(writer);
dto.setWritedate(writedate);
dto.setReaded(readed);
list.add(dto);
} while (rs.next());
} // if
} catch (SQLException e1) {
e1.printStackTrace();
}finally {
try {
rs.close();
pstmt.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
// 포워딩~
request.setAttribute("list", list);
String path = "/days05/board/list.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} // doGet
*/
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
list.jsp - 목록 화면
<%@page import="days05.board.PageBlock"%>
<%@page import="java.util.Iterator"%>
<%@page import="days05.board.BoardDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
ArrayList<BoardDTO> list =
(ArrayList<BoardDTO>)request.getAttribute("list");
PageBlock pageBlock = (PageBlock)request.getAttribute("pageBlock");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>list.jsp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
table, td, th {
border: solid 1px gray;
}
table {
border-spacing: 3px;
border-collapse: separate;
}
table, tr, td {
/* border-radius: 3px; */
/* padding:3px; */
}
tbody tr td:nth-of-type(2) {
text-align: left;
}
a {
text-decoration: none;
color: black;
}
a:hover {
color: red;
}
</style>
<!-- 페이징 처리 style -->
<style>
.pagination {
margin: 0 auto;
display: flex;
justify-content: center;
}
.pagination a {
color: black;
float: left;
padding: 4px 8px;
text-decoration: none;
transition: background-color .3s;
}
.pagination a.active {
background-color: dodgerblue;
color: white;
}
.pagination a:hover:not (.active ) {
background-color: #ddd;
}
</style>
<style>
.searchWord {
background-color: yellow;
color: red;
}
</style>
<style>
.title {
display: inline-block;
white-space: nowrap;
width: 90%;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
<script>
$(document).ready(function (){
// list.htm?write=success
if( '<%= request.getParameter("write") %>' == 'success' ){
alert("글 쓰기 완료!!!");
}
// 상태 유지
$("#searchCondition").val( '${ requestScope.searchCondition }');
$("#searchWord").val('${ param.searchWord}');
// http://localhost/jspPro/cstvsboard/list.htm?currentPage=3
// &searchCondition=1&searchWord=jsp 파라미터 추가...
$(".pagination a").attr("href", function (i, val){
return val
+"&searchCondition=${ requestScope.searchCondition}&searchWord=${ param.searchWord}";
});
/*
$(".pagination a")
.eq("${ pageBlock.currentPage / 10 -1 }")
.addClass("active")
.attr("href","#");
*/
// ?seq=1
$("a.title").attr("href", function (i, val){
return val
+"¤tPage=${ param.currentPage }&searchCondition=${ requestScope.searchCondition}&searchWord=${ param.searchWord}";
});
});
</script>
</head>
<body>
<!-- <h3>list.jsp</h3> -->
<div align="center">
<h2>목록 보기</h2>
<a href="/jspPro/cstvsboard/write.htm">글쓰기</a>
<table style="width:600px;">
<thead>
<tr>
<th width="10%">번호</th>
<th width="45%">제목</th>
<th width="17%">작성자</th>
<th width="20%">등록일</th>
<th width="10%">조회</th>
</tr>
</thead>
<tbody>
<%
if( list == null ){
%>
<tr><td colspan="5">등록된 게시글이 없습니다.</td></tr>
<%
}else{
Iterator<BoardDTO> ir = list.iterator();
while( ir.hasNext() ){
BoardDTO dto = ir.next();
%>
<tr align="center">
<td><%= dto.getSeq() %></td>
<%-- <td><%= dto.getTitle() %></td> --%>
<td>
<a class="title" href="/jspPro/cstvsboard/content.htm?seq=<%= dto.getSeq() %>"><%= dto.getTitle() %></a>
<%
if( dto.isNewmark() ){
%><img src="/jspPro/days05/board/images/ico-new.gif" alt="" /><%
}
%>
</td>
<td>
<%
if( dto.getWriter().equals("kenik") ){
%><img src="/jspPro/days05/board/images/star.gif" alt="" /><%
}
%>
<a href="mailto:<%= dto.getEmail() %>"><%= dto.getWriter() %></a>
</td>
<td><%= dto.getWritedate() %></td>
<td><%= dto.getReaded() %></td>
</tr>
<%
} // while
} // if
%>
</tbody>
<tfoot>
<tr>
<td colspan="5" align="center">
<div class="pagination">
<!-- a[href='#']*11>{ $ } -->
<!--
<a href="#" class="active"> 1 </a>
<a href="#"> 2 </a>
<a href="#"> 3 </a>
<a href="#"> 4 </a>
<a href="#"> 5 </a>
<a href="#"> 6 </a>
<a href="#"> 7 </a>
<a href="#"> 8 </a>
<a href="#"> 9 </a>
<a href="#"> 10 </a>
<a href="#"> » </a>
-->
<%-- [ 파라미터를 순차적으로 연결한 경우 ]
// http://localhost/jspPro/cstvsboard/list.htm?currentPage=3
// &searchCondition=1&searchWord=jsp 추가...
<%
if( pageBlock.isPrev() ){
%>
<a href="/jspPro/cstvsboard/list.htm?currentPage=<%= pageBlock.getStart() -1 %>&searchCondition=${ requestScope.searchCondition }&searchWord=${ param.searchWord} ""> « </a>
<%
}
for(int i = pageBlock.getStart() ; i <= pageBlock.getEnd() ; i++ ){
%>
<a class="<%= i==pageBlock.getCurrentPage() ? "active":"" %>
" href="/jspPro/cstvsboard/list.htm?currentPage=<%= i %>&searchCondition=${ requestScope.searchCondition }&searchWord=${ param.searchWord} "><%= i %></a>
<%
}
if( pageBlock.isNext() ){
%>
<a href="/jspPro/cstvsboard/list.htm?currentPage=<%= pageBlock.getEnd() + 1 %>&searchCondition=${ requestScope.searchCondition }&searchWord=${ param.searchWord} ""> » </a>
<%
}
%>
--%>
<%
if( pageBlock.isPrev() ){
%>
<a href="/jspPro/cstvsboard/list.htm?currentPage=<%= pageBlock.getStart() -1 %>"> « </a>
<%
}
for(int i = pageBlock.getStart() ; i <= pageBlock.getEnd() ; i++ ){
%>
<a class="<%= i==pageBlock.getCurrentPage() ? "active":"" %>" href="/jspPro/cstvsboard/list.htm?currentPage=<%= i %>"><%= i %></a>
<%
}
if( pageBlock.isNext() ){
%>
<a href="/jspPro/cstvsboard/list.htm?currentPage=<%= pageBlock.getEnd() + 1 %>"> » </a>
<%
}
%>
</div>
</td>
</tr>
<tr>
<td colspan="5" align="center">
<form>
<select name="searchCondition" id="searchCondition">
<option value="1">title</option>
<option value="2">content</option>
<option value="3">writer</option>
<option value="4">title+content</option>
</select>
<input type="text" name="searchWord" id="searchWord" />
<input type="submit" value="search" />
</form>
</td>
</tr>
</tfoot>
</table>
<!-- GET 방식 요청 -->
<a href="/jspPro/cstvsboard/write.htm">글쓰기</a>
</div>
</body>
</html>
<%--
${} js주석, html주석 X
/*
$("#searchCondition").val(
'${ empty param.searchCondition ? 1 : param.searchCondition }');
*/
// ?searchCondition param.searchCondition
// request Scope searchCondition
// ${} requestScope EL 에서만 사용할 수 있는 객체
--%>
Write.java - 글쓰기와 관련된 서블릿
package days05.board;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
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.util.DBConn;
/**
* Servlet implementation class Write
*/
@WebServlet("/cstvsboard/write.htm")
public class Write extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Write() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//System.out.println("> Write.java doGet()...");
String path = "/days05/board/write.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String writer = request.getParameter("writer");
String pwd = request.getParameter("pwd");
String email = request.getParameter("email");
String title = request.getParameter("title");
int tag = Integer.parseInt( request.getParameter("tag") );
String content = request.getParameter("content");
Connection con = DBConn.getConnection();
PreparedStatement pstmt = null;
String sql = "INSERT INTO TBL_CSTVSBOARD "
+ " ( seq, writer, pwd, email, title, tag, content ) "
+ " VALUES ( SEQ_TBL_CSTVSBOARD.NEXTVAL, ?, ?, ?, ?, ?, ? )";
int rowCount = 0;
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, writer );
pstmt.setString(2, pwd );
pstmt.setString(3, email );
pstmt.setString(4, title );
pstmt.setInt(5, tag );
pstmt.setString(6, content );
rowCount = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
// redirect list.htm
String location = "/jspPro/cstvsboard/list.htm";
if( rowCount == 1 ) location +="?write=success";
response.sendRedirect(location);
} // doPost
} // class
write.jsp - 글쓰기 화면
<%@page import="java.util.Iterator"%>
<%@page import="days05.board.BoardDTO"%>
<%@page import="java.util.ArrayList"%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>write.jsp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
table, td, th {
border: solid 1px gray;
}
table {
border-spacing: 3px;
border-collapse: separate;
}
table, tr, td {
/* border-radius: 3px; */
/* padding:3px; */
}
</style>
<script>
$(document).ready(function (){
});
</script>
</head>
<body>
<!-- <h3>write.jsp</h3> -->
<div align="center">
<h2>글 쓰기</h2>
<!-- [기억] action 속성 설정 되지 않으면 http://localhost/jspPro/cstvsboard/write.htm 요청 -->
<form method="post">
<table style="padding: 2px; width: 600px">
<tr>
<td colspan="2" align="center"><b>글을 적어주세요</b></td>
</tr>
<tr>
<td align="center">이름</td>
<td><input type="text" name="writer" size="15"
autofocus="autofocus" required="required"></td>
</tr>
<tr>
<td align="center">비밀번호</td>
<td><input type="password" name="pwd" size="15" required="required"></td>
</tr>
<tr>
<td align="center">Email</td>
<td><input type="email" name="email" size="50" ></td>
</tr>
<tr>
<td align="center">제목</td>
<td><input type="text" name="title" size="50" required="required"></td>
</tr>
<tr>
<td align="center">내용</td>
<td><textarea name="content" cols="50" rows="10"></textarea></td>
</tr>
<tr>
<td align="center">HTML</td>
<td><input type="radio" name="tag" value="1" checked>적용
<input type="radio" name="tag" value="0">비적용</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="작성 완료">
<input type="reset" value="다시 작성">
<a href="/jspPro/cstvsboard/list.htm">Home</a>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Content.java - 게시글 내용보기와 관련된 서블릿
package days05.board;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.util.DBConn;
/**
* Servlet implementation class Content
*/
@WebServlet("/cstvsboard/content.htm")
public class Content extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Content() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int seq = Integer.parseInt(request.getParameter("seq"));
Connection con = DBConn.getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
// 1. 조회수 증가
String sql = "UPDATE TBL_CSTVSBOARD "
+ " SET readed = readed + 1 "
+ " WHERE seq = ?";
int rowCount = 0;
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, seq);
rowCount = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 2. 게시글 얻어오는 코딩.
sql = "SELECT seq, writer, title, content, readed, writedate , email "
+ " FROM TBL_CSTVSBOARD "
+ " WHERE seq = ?";
BoardDTO dto = null;
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, seq);
rs = pstmt.executeQuery();
if (rs.next()) {
// seq, writer, title, content, readed, writedate
dto = new BoardDTO();
dto.setSeq( rs.getInt("seq"));
dto.setWriter(rs.getString("writer"));
dto.setTitle(rs.getString("title"));
dto.setContent(rs.getString("content"));
dto.setReaded( rs.getInt("readed"));
dto.setWritedate(rs.getDate("writedate"));
dto.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
request.setAttribute("dto", dto);
String path = "/days05/board/content.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} // doGet
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
content.jsp - 내용보기 화면
<%@page import="days05.board.BoardDTO"%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
BoardDTO dto = (BoardDTO) request.getAttribute("dto");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>content.jsp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- jquery.ui -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- bootstrap4 -->
<!--
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
-->
<style>
table{
border-spacing: 3px;
border-collapse: separate;
}
table, tr, td {
border:solid 1px gray;
/* border-radius: 3px;
padding:3px; */
}
#tblContent{
width:600px;
}
</style>
<script>
$(document).ready(function (){
$("#homeLink")
.attr("href"
, "/jspPro/cstvsboard/list.htm?currentPage=${ param.currentPage }&searchCondition=${ param.searchCondition}&searchWord=${ param.searchWord}");
$("#btnModalDelete").on("click", function(event) {
// 객체.메서드("open")
dialog.dialog("open");
});
$("#cancel").on("click", function(event) {
// 객체.메서드("open")
dialog.dialog("close");
});
dialog = $( "#dialog-form" ).dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
/* "Create an account": addUser,
Cancel: function() {
dialog.dialog( "close" );
} */
},
close: function() {
form[ 0 ].reset();
//allFields.removeClass( "ui-state-error" );
}
});
form = dialog.find( "form" );
});
</script>
</head>
<body>
<div align="center">
<h2>내용보기</h2>
<!-- <table id="tblContent" class="table"> -->
<table id="tblContent">
<tr>
<td>이름</td>
<td><%= dto.getWriter() %></td>
<td>등록일</td>
<td><%= dto.getWritedate() %></td>
</tr>
<tr>
<td>Email</td>
<td><a href="mailto:<%= dto.getEmail() %>"><%= dto.getEmail() %></a></td>
<td>조회</td>
<td><%= dto.getReaded() %></td>
</tr>
<tr>
<td>제목</td>
<td colspan="3"><%= dto.getTitle() %></td>
</tr>
<tr>
<td colspan="4" style="padding:15px;height: 200px;text-align: left;vertical-align: top">
<%= dto.getContent() %>
</td>
</tr>
<tr>
<td colspan="4" align="center">
<a class="btn btn-secondary" href="/jspPro/cstvsboard/edit.htm?seq=<%= dto.getSeq() %>" id="editLink">수정하기</a>
<a class="btn btn-secondary" href="/jspPro/cstvsboard/delete.htm?seq=<%= dto.getSeq() %>" id="deleteLink">삭제하기</a>
<a class="btn btn-secondary" href="#" id="homeLink">Home</a>
<input class="btn btn-secondary" type="button" id="btnModalDelete" value="모달창으로 글 삭제">
</td>
</tr>
</table>
</div>
<!-- 삭제 모달창 -->
<div id="dialog-form" align="center" title="삭제">
<h2>삭제하기</h2>
<form action="/jspPro/cstvsboard/delete.htm" method="post">
<table>
<tr>
<td colspan="2" align="center"><b>글을 삭제합니다</b></td>
</tr>
<tr>
<td align="center">비밀번호</td>
<td>
<input type="password" name="pwd" size="15" autofocus="autofocus">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="삭제">
<!-- <input type="button" onClick="javascript:history.back();" value="취소"> -->
<input type="button" id="cancel" value="취소">
</td>
</tr>
</table>
<input type="hidden" name="seq" value="${ param.seq }" />
</form>
</div>
</body>
</html>
Delete.java - 게시글 삭제와 관련된 서블릿
모달창 삭제도 존재
package days05.board;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.util.DBConn;
/**
* Servlet implementation class Delete
*/
@WebServlet("/cstvsboard/delete.htm")
public class Delete extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Delete() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = "/days05/board/delete.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String pPwd = request.getParameter("pwd");
String seq = request.getParameter("seq");
Connection con = null;
PreparedStatement pstmt = null;
int rowCount = 0;
ResultSet rs = null;
String oPwd = null;
try {
String sql = "SELECT pwd FROM TBL_CSTVSBOARD "
+ " WHERE seq = ?";
con = DBConn.getConnection();
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(seq) );
rs = pstmt.executeQuery();
if( rs.next() ) {
oPwd = rs.getString("pwd");
}
rs.close();
if( !oPwd.equals(pPwd)) {
request.setAttribute("error", "비밀번호가 틀립니다.");
doGet(request, response);
return;
}
// 비밀번호가 일치하기 때문에 게시글 삭제
sql = "DELETE FROM TBL_CSTVSBOARD "
+" WHERE seq = ? ";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(seq) );
rowCount = pstmt.executeUpdate();
} catch (Exception e) {
//System.out.println("> Write.java doPost()... 예외발생!!");
e.printStackTrace();
} finally {
try {
pstmt.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
String location = "/jspPro/cstvsboard/list.htm";
if( rowCount == 1 ) location +="?delete=success";
response.sendRedirect(location);
} // doPost
} // class
delete.jsp - 삭제 화면
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>delete.jsp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
table , td, th {
border:solid 1px gray;
}
table{
border-spacing: 3px;
border-collapse: separate;
}
table, tr, td {
/* border-radius: 3px; */
/* padding:3px; */
}
table{
width: 600px;
}
</style>
<script>
$(document).ready(function (){
});
</script>
</head>
<body>
<div align="center">
<h2>삭제하기</h2>
<form method="post">
<table>
<tr>
<td colspan="2" align="center"><b>글을 삭제합니다</b></td>
</tr>
<tr>
<td align="center">비밀번호</td>
<td>
<input type="password" name="pwd" size="15" autofocus="autofocus">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="삭제">
<!-- <input type="button" onClick="javascript:history.back();" value="취소"> -->
<input type="button" id="cancel" value="취소">
</td>
</tr>
</table>
<input type="hidden" name="seq" value="${ param.seq }" />
</form>
</div>
<%
String error = (String) request.getAttribute("error");
if( error != null){
%>
<script>
alert("<%= error %>");
</script>
<%
}
%>
</body>
</html>
Edit.java - 게시글 수정과 관련된 서블릿
package days05.board;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.util.DBConn;
/**
* Servlet implementation class Edit
*/
@WebServlet("/cstvsboard/edit.htm")
public class Edit extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Edit() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pSeq = request.getParameter("seq");
int seq = pSeq == null ? 0 : Integer.parseInt( pSeq );
String sql = "SELECT seq, writer, email, title, content, readed, writedate, tag, pwd "
+ " FROM TBL_CSTVSBOARD "
+ " WHERE seq = ?";
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
BoardDTO dto = null;
con = DBConn.getConnection();
try {
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, seq);
rs = pstmt.executeQuery();
if (rs.next()) {
dto = new BoardDTO();
dto.setSeq(rs.getInt("seq"));
dto.setWriter(rs.getString("writer"));
dto.setEmail(rs.getString("email"));
dto.setTitle(rs.getString("title"));
dto.setWritedate(rs.getDate("writedate"));
dto.setReaded(rs.getInt("readed"));
dto.setTag( rs.getInt("tag"));
dto.setContent(rs.getString("content"));
} //
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
rs.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
// 포워딩
request.setAttribute("dto", dto);
String path = "/days05/board/edit.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} // doGet
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String seq = request.getParameter("seq"); // int
String writer = request.getParameter("writer");
String pwd = request.getParameter("pwd");
String email = request.getParameter("email");
String title = request.getParameter("title");
String tag = request.getParameter("tag"); // int
String content = request.getParameter("content");
String sql = "UPDATE TBL_CSTVSBOARD "
+ " SET email = ?, title = ? , tag = ?, content = ? "
+ " WHERE SEQ = ? AND PWD = ?";
Connection con = null;
PreparedStatement pstmt = null;
int rowCount = 0;
con = DBConn.getConnection();
try {
pstmt = con.prepareStatement(sql);
pstmt.setString(1, email );
pstmt.setString(2, title);
pstmt.setInt(3, Integer.parseInt( tag ) );
pstmt.setString(4, content);
pstmt.setInt(5, Integer.parseInt( seq ) );
pstmt.setString(6, pwd );
rowCount = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
DBConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} // try
if (rowCount == 1) {
String location =
String.format("/jspPro/cstvsboard/content.htm?seq=%s&edit=%s"
, seq , "success");
response.sendRedirect(location);
} else {
}
} // doPost
} // class
edit.jsp - 게시글 수정 화면
<%@page import="days05.board.BoardDTO"%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
BoardDTO dto = (BoardDTO)request.getAttribute("dto");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>edit.jsp</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
table, td, th {
border: solid 1px gray;
}
table {
border-spacing: 3px;
border-collapse: separate;
}
table, tr, td {
/* border-radius: 3px; */
/* padding:3px; */
}
table {
width: 600px;
}
</style>
<script>
$(document).ready(function (){
});
</script>
</head>
<body>
<div align="center">
<h2>수정하기</h2>
<!-- [중요사항] action 속성 X -->
<form method="post">
<table>
<tr>
<td colspan="2" align="center"><b>글을 수정합니다</b></td>
</tr>
<tr>
<td align="center">이름</td>
<td><input type="text" readonly name="writer" size="15"
value="<%= dto.getWriter() %>"></td>
</tr>
<tr>
<td align="center">Email</td>
<td><input type="email" name="email" size="50"
value="<%= dto.getEmail() %>"></td>
</tr>
<tr>
<td align="center">제목</td>
<td><input type="text" name="title" size="50"
value="<%= dto.getTitle() %>"></td>
</tr>
<tr>
<td align="center">내용</td>
<td><textarea name="content" cols="50" rows="10"><%= dto.getContent() %></textarea>
</td>
</tr>
<tr>
<td align="center">HTML</td>
<td>
<input type="radio" name="tag" value="1">적용
<input type="radio" name="tag" value="0">비적용
<script>
// JS 에서 EL 사용하는 방법 "EL 사용가능"
// :radio == input type=radio
$(":radio[value=<%= dto.getTag() %>]").attr("checked", "checked");
</script>
</td>
</tr>
<tr>
<td align="center">비밀번호</td>
<td><input type="password" name="pwd" size="15"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="작성 완료">
<input type="button" onClick="javascript:history.back();" value="이전으로">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
'JSP' 카테고리의 다른 글
[days07] 쿠키를 사용해 로그인 처리(상태관리)(회원/비회원/관리자) (0) | 2021.01.04 |
---|---|
[days06] 쿠키 (쿠키수정 추가 필요) (0) | 2021.01.01 |
[days05] 자바 빈즈(Java Beans) (0) | 2020.12.29 |
[days05] 페이지 모듈화 - <%@include %>지시자와 <jsp:include>액션태그 (0) | 2020.12.29 |
[days05] JSP 예외처리 (0) | 2020.12.29 |