--------------------------------------------------------
상담 게시판 글 삭제 (패스워드 검사 과정 추가)
//consultView.jsp -> 삭제 메뉴에 링크 추가
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="com.test.*" %>
<%
ConsultationDTO dto
= (ConsultationDTO)request.getAttribute("dto");
String sid = dto.getSid();
String name = dto.getName();
String title = dto.getTitle();
String wdate = dto.getWdate();
String content = dto.getContent();
//----------------------------------
//출력 오류 처리 필요
//내용에 HTML 태그가 포함된 경우
//HTML 태그가 태그로 보이는게 아니라 실행 코드가 되버린다.
//태그를 문자열로 변경시켜야 한다.
name = name.replaceAll("<", "<").replaceAll(">", ">");
title = title.replaceAll("<", "<").replaceAll(">", ">");
content = content.replaceAll("<", "<").replaceAll(">", ">");
//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요
content = content.replaceAll(" ", " ");
content = content.replaceAll("\n", "<br>");
content = content.replaceAll("\t", " ");
//----------------------------------
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Java 전문 교육센터</title>
<link rel="stylesheet" type="text/css" href="common.css">
<link rel="stylesheet" type="text/css" href="table.css">
</head>
<body>
<div>
<div>
<h1>Java 전문 교육센터</h1>
<a href="javascript:">[교육원소개]</a>
<a href="javascript:">[교육과정안내]</a>
<a href="javascript:">[취업지원센터]</a>
<a href="consultList.con">[상담게시판]</a>
<a href="member.mem">[회원가입]</a>
<a href="login.mem">[로그인]</a>
<hr>
</div>
<div>
<h3>[상담게시판_내용보기]</h3>
<table cellpadding="5" class="style01 borderTop">
<tr>
<td class="bTitle">
<h3><!-- 상담 게시판을 오픈합니다. --><%=title%></h3>
<span><!-- 관리자 --><%=name%></span>
<span><!-- 2010-01-01 --><%=wdate%></span>
</td>
</tr>
<tr>
<td class="bTitle" style="padding-top:20px;padding-bottom:20px;"><!-- 많은 이용 바랍니다. --><%=content%></td>
</tr>
</table>
<div style="margin-top:10px;">
<a href="consultList.con">[목록보기]</a>
<a href="">[답글쓰기]</a>
<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>
<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>
</div>
</div>
</div>
</body>
</html>
//ConsultationServlet.java
package com.test;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ConsultationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGetPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGetPost(req, resp);
}
protected void doGetPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//서블릿 주소 분석
String uri = req.getRequestURI();
if (uri.indexOf("consultList.con") != -1) {
consultList(req, resp);
}
if (uri.indexOf("consultInsertForm.con") != -1) {
consultInsertForm(req, resp);
}
if (uri.indexOf("consultInsert.con") != -1) {
consultInsert(req, resp);
}
if (uri.indexOf("consultView.con") != -1) {
consultView(req, resp);
}
if (uri.indexOf("consultModifyForm.con") != -1) {
consultModifyForm(req, resp);
}
if (uri.indexOf("consultModify.con") != -1) {
consultModify(req, resp);
}
if (uri.indexOf("consultRemoveForm.con") != -1) {
consultRemoveForm(req, resp);
}
}
private void consultList(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ArrayList<ConsultationDTO> arrayList
= new ArrayList<ConsultationDTO>();
ConsultationDAO dao = new ConsultationDAO();
try {
dao.connect();
arrayList = dao.lists();
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
dao.close();
} catch (SQLException e) {
}
}
req.setAttribute("arrayList", arrayList);
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultList.jsp");
dispatcher.forward(req, resp);
}
private void consultInsertForm(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultInsertForm.jsp");
dispatcher.forward(req, resp);
}
private void consultInsert(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//데이터 수신
//데이터베이스 연결
//INSERT 쿼리 메소드 호출
//consultList.con 으로 페이지 이동
req.setCharacterEncoding("euc-kr");
String name = req.getParameter("name");
String pw = req.getParameter("pw");
String title = req.getParameter("title");
String content = req.getParameter("content");
//-----------------------------
//입력 오류 처리 필요
//오라클에서는 입력 데이터에
//작은따옴표(')가 있으면
//입력 오류 발생됨
//작은따옴표(')를 두 번 입력('')하면 해결됨.
name = name.replaceAll("'", "''");
pw = pw.replaceAll("'", "''");
title = title.replaceAll("'", "''");
content = content.replaceAll("'", "''");
//-----------------------------
ConsultationDAO dao = new ConsultationDAO();
try {
dao.connect();
ConsultationDTO dto = new ConsultationDTO();
dto.setName(name);
dto.setPw(pw);
dto.setTitle(title);
dto.setContent(content);
dao.add(dto);
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
dao.close();
} catch (SQLException e) {
}
}
String url = String.format("consultList.con");
resp.sendRedirect(url);
}
private void consultView(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//글번호 수신
//데이터베이스 연결
//글번호에 해당하는 글 정보 읽어온다.
//글 정보(ConsultationDTO)를 출력 페이지로 전달
//글 정보 출력 페이지(consultView.jsp)로 이동
String sid = req.getParameter("sid");
ConsultationDTO dto = new ConsultationDTO();
ConsultationDAO dao = new ConsultationDAO();
try {
dao.connect();
dto = dao.searchBySid(sid);
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
dao.close();
}catch(Exception e){
}
}
req.setAttribute("dto", dto);
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultView.jsp");
dispatcher.forward(req, resp);
}
private void consultModifyForm(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//글번호 수신
//작성자, 패스워드 수신
//처음에는 패스워드 검사 페이지로 이동-> consultPW.jsp
//작성자, 패스워드가 수신된 경우는 패스워드 검사 과정 수행
//패스워드 검사 결과에 따라서
//맞는 경우는 수정 페이지로 이동 -> consultModifyForm.jsp
//틀린 경우는 에러 메시지 출력-> consultPW.jsp
req.setCharacterEncoding("euc-kr");
String sid = req.getParameter("sid");
String name = req.getParameter("name");
String pw = req.getParameter("pw");
if (name == null && pw == null) {
//consultView.jsp -> consultPW.jsp
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultPW.jsp");
dispatcher.forward(req, resp);
} else {
//consultPW.jsp -> consultPW.jsp
//패스워드 검사 과정
ConsultationDAO dao = new ConsultationDAO();
ConsultationDTO dto = null;
try {
dao.connect();
ConsultationDTO sdto = new ConsultationDTO();
sdto.setSid(sid);
sdto.setName(name);
sdto.setPw(pw);
dto = dao.searchByPw(sdto);
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
dao.close();
}catch(Exception e){
}
}
if (dto != null) {
req.setAttribute("dto", dto);
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultModifyForm.jsp");
dispatcher.forward(req, resp);
} else {
req.setAttribute("error", "true");
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultPW.jsp");
dispatcher.forward(req, resp);
}
}
}
private void consultModify(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
private void consultRemoveForm(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("euc-kr");
String sid = req.getParameter("sid");
String name = req.getParameter("name");
String pw = req.getParameter("pw");
if (name == null && pw == null) {
//consultView.jsp -> consultPW.jsp
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultPW.jsp");
dispatcher.forward(req, resp);
} else {
//consultPW.jsp -> consultPW.jsp
//패스워드 검사 과정
ConsultationDAO dao = new ConsultationDAO();
ConsultationDTO dto = null;
try {
dao.connect();
ConsultationDTO sdto = new ConsultationDTO();
sdto.setSid(sid);
sdto.setName(name);
sdto.setPw(pw);
dto = dao.searchByPw(sdto);
}catch(Exception e){
System.out.println(e.toString());
}finally{
try {
dao.close();
}catch(Exception e){
}
}
if (dto != null) {
//삭제 과정 추가 -> sid 필요
try {
dao.connect();
dao.remove(sid);
} catch(Exception e){
System.out.println(e.toString());
} finally {
try {
dao.close();
} catch (SQLException e) {
}
}
//목록 페이지로 이동
String url = String.format("consultList.con");
resp.sendRedirect(url);
} else {
req.setAttribute("error", "true");
RequestDispatcher dispatcher
= req.getRequestDispatcher("consultPW.jsp");
dispatcher.forward(req, resp);
}
}
}
}
//ConsultationDAO.java
package com.test;
import java.sql.*;
import java.util.*;
public class ConsultationDAO {
private Connection conn;
public void connect()
throws ClassNotFoundException, SQLException {
conn = DBConn.getConnection();
}
public void close()
throws SQLException {
DBConn.close();
}
//상담 게시판 글목록 출력
public ArrayList<ConsultationDTO> lists()
throws SQLException {
ArrayList<ConsultationDTO> arrayList
= new ArrayList<ConsultationDTO>();
String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate FROM consultation ORDER BY sid DESC");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
ConsultationDTO dto = new ConsultationDTO();
dto.setSid(rs.getString("sid"));
dto.setName(rs.getString("name"));
dto.setTitle(rs.getString("title"));
dto.setWdate(rs.getString("wdate"));
arrayList.add(dto);
}
rs.close();
return arrayList;
}
//상담 게시판 글 입력
public int add(ConsultationDTO dto)
throws SQLException {
int result = 0;
String sql = String.format("INSERT INTO consultation (sid, name, pw, title, content, wdate) VALUES (consultationSeq.nextVal,'%s',encrypt('%s', '%s'),'%s','%s',SYSDATE)", dto.getName(), dto.getPw(), dto.getName(), dto.getTitle(), dto.getContent());
Statement stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
return result;
}
public ConsultationDTO searchBySid(String sid)
throws SQLException {
ConsultationDTO dto = new ConsultationDTO();
String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultation WHERE sid=%s", sid);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
dto.setSid(rs.getString("sid"));
dto.setName(rs.getString("name"));
dto.setTitle(rs.getString("title"));
dto.setContent(rs.getString("content"));
dto.setWdate(rs.getString("wdate"));
}
rs.close();
return dto;
}
public ConsultationDTO searchByPw(ConsultationDTO dto)
throws SQLException {
ConsultationDTO sdto = null;
String sql = String.format("SELECT sid, title, content FROM consultation WHERE sid=%s AND name='%s' AND pw=encrypt('%s', '%s')", dto.getSid(), dto.getName(), dto.getPw(), dto.getName());
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()) {
sdto = new ConsultationDTO();
sdto.setSid(rs.getString("sid"));
sdto.setTitle(rs.getString("title"));
sdto.setContent(rs.getString("content"));
}
rs.close();
return sdto;
}
public int remove(String sid)
throws SQLException {
int result = 0;
String sql = String.format("DELETE FROM consultation WHERE sid=%s", sid);
Statement stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
return result;
}
}
//consultPW.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%
String sid = request.getParameter("sid");
String error = "false";
Object result = request.getAttribute("error");
if (result != null) {
error = (String)result;
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Java 전문 교육센터</title>
<link rel="stylesheet" type="text/css" href="common.css">
<link rel="stylesheet" type="text/css" href="table.css">
<script type="text/javascript" src="consultation.js"></script>
<script type="text/javascript">
function msg() {
if (<%=error%>) {
alert("작성자 또는 패스워드가 틀렸습니다.");
}
}
</script>
</head>
<body onload="msg()">
<div>
<div>
<h1>Java 전문 교육센터</h1>
<a href="javascript:">[교육원소개]</a>
<a href="javascript:">[교육과정안내]</a>
<a href="javascript:">[취업지원센터]</a>
<a href="consultList.con">[상담게시판]</a>
<a href="member.mem">[회원가입]</a>
<a href="login.mem">[로그인]</a>
<hr>
</div>
<div>
<h3>[상담게시판_패스워드 확인]</h3>
해당 게시물의 수정, 삭제를 위해 작성자, 패스워드를 확인합니다.
<%-- action 속성을 생략하면 수정, 삭제 두 가지 용도로 모두 사용 가능 --%>
<form method="post" id="pwForm">
<%-- 수정, 삭제를 위해서 sid 값을 재전송해야 한다. --%>
<input type="hidden" name="sid" value="<%=sid%>">
<table cellpadding="5" style="style01">
<tr>
<td>작성자*</td><td><input type="text" id="name" name="name" ><span id="nameMsg" style="color:red; display:none;">1~20자 이름 입력</span></td>
</tr>
<tr>
<td>패스워드*</td><td><input type="password" id="pw" name="pw"><span id="pwMsg" style="color:red; display:none;">1~20자 패스워드 입력</span></td>
</tr>
</table>
<a href="javascript:pwFormSubmit()">[확인]</a>
<a href="">[취소]</a>
</form>
</div>
</div>
</body>
</html>
//요청주소
http://localhost:8090/ConsultationServlet_20121207/consultList.con
----------------------------------------------------------
상담게시판 글 검색 (패스워드 검사 과정 추가)
'Java > JSP & Servlet' 카테고리의 다른 글
[20121212] 21일차 (상담게시판) (0) | 2012.12.18 |
---|---|
[20121211] 20일차 (상담게시판) (0) | 2012.12.18 |
[20121207] 18일차 (상담게시판) (0) | 2012.12.18 |
[20121206] 17일차 (0) | 2012.12.14 |
[20121205] 16일차 (JSP / Servlet / JDBC 연동) (0) | 2012.12.05 |
WRITTEN BY