------------------------------------------------

상담 게시판 패스워드 변경 (사용자)



//memberInfo.jsp -> [패스워드변경] 메뉴에 링크 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();

String[] array = {"관리자", "직원", "학생", "회원가입"};

String grade = array[dto.getGrade()-1];

%>        

<!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() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle"><%=id%></td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle"><%=name%></td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle"><%=email%></td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle"><%=tel%></td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle"><%=grade%></td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자, 직원 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1' || sessionScope.grade == '2'}">

<a href="memberList.mem">[*회원명단]</a>

</c:if>


<a href="memberPWModifyForm.mem">[패스워드변경]</a>

<a href="">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>





//MemberServlet.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;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

if (uri.indexOf("memberList.mem") != -1) {

memberList(req,resp);

}

if (uri.indexOf("adminUpdateForm.mem") != -1) {

adminUpdateForm(req,resp);

}

if (uri.indexOf("adminUpdate.mem") != -1) {

adminUpdate(req,resp);

}

if (uri.indexOf("memberPWModifyForm.mem") != -1) {

memberPWModifyForm(req,resp);

}

if (uri.indexOf("memberPWModify.mem") != -1) {

memberPWModify(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

//로그인 상태 확인 부분 추가

if (session.getAttribute("id") == null) {

resp.sendRedirect("login.mem");

}

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}


private void memberList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자, 직원만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1

&& (Integer)session.getAttribute("grade") != 2) {

resp.sendRedirect("login.mem");

}

//----------------------------------

//등급별 회원 명단 출력 부분 추가

String grade = req.getParameter("grade");

if (grade == null) {

grade = "0";

}

//등급별로 쿼리의 다른 조건식 생성

String wheres = "";

if (!grade.equals("0")) {

wheres = String.format("WHERE grade=%s", grade);

}

//----------------------------------

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

//----------------------------------

//등급별 출력 이전 쿼리

//arrayList = dao.lists();

//등급별 출력 이후 쿼리

arrayList = dao.lists(wheres);

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberList.jsp");

dispatcher.forward(req, resp);

}


private void adminUpdateForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//아이디 수신

//해당 아이디에 대한 개인정보(MemberDTO) 읽어오기

//수정 페이지에 전송 준비

//수정 페이지(adminUpdateForm.jsp)로 이동

String id = req.getParameter("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("adminUpdateForm.jsp");

dispatcher.forward(req, resp);

}

private void adminUpdate(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//데이터 수신

//UPDATE 쿼리 메소드(adminModify(MemberDTO dto)) 호출

//memberList.con으로 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

String grade = req.getParameter("grade");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dto.setGrade(Integer.parseInt(grade));

dao.adminModify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("memberList.mem");

resp.sendRedirect(url);

}


private void memberPWModifyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberPWModifyForm.jsp");

dispatcher.forward(req, resp);

}


private void memberPWModify(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pw = req.getParameter("pw");

String newpw = req.getParameter("newpw");

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

int result = 0;

try {

dao.connect();

result = dao.pwModify(id, pw, newpw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (result == 1) {

//정보 페이지로 이동

String url = String.format("memberInfo.mem");

resp.sendRedirect(url);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberPWModifyForm.jsp");

dispatcher.forward(req, resp);

}

}

}





//memberPWModifyForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%

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>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[회원정보_패스워드변경]</h3>

<form action="memberPWModify.mem" method="post" id="memberPwForm">

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="200px">*기존 패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg" style="color:red; display:none;">1~20자 이내 패스워드 입력해야 합니다.</span></td>

</tr>

<tr>

<td class="tName" width="200px">*새로운 패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="newpw" name="newpw"><span id="newpwMsg" style="color:red; display:none;">1~20자 이내 패스워드 입력해야 합니다.</span></td>

</tr>

</table>

<br><br>

<a href="javascript:memberPwFormSubmit()">[패스워드변경]</a>

<a href="memberInfo.mem">[회원정보]</a>

</form>

</div>

</div>


</body>

</html>




//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.con?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

obj.submit();

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.jsp";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------




function memberPwFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberPwForm");


var pw = document.getElementById("pw");

var newpw = document.getElementById("newpw");

var pwMsg = document.getElementById("pwMsg");

var newpwMsg = document.getElementById("newpwMsg");

pwMsg.style.display = "none";

newpwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (newpw.value == "" || newpw.value.length > 20) {

newpwMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}





//MemberDAO.java

package com.test;


import java.sql.*;

import java.util.ArrayList;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<MemberDTO> lists() 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember ORDER BY grade ASC, name ASC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<MemberDTO> lists(String wheres) 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember %s ORDER BY grade ASC, name ASC", wheres);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int adminModify(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET name='%s', email='%s', tel='%s', grade=%d WHERE id='%s'", dto.getName(), dto.getEmail(), dto.getTel(), dto.getGrade(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int pwModify(String id, String pw, String newpw)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET pw=encrypt('%s', '%s') WHERE pw=encrypt('%s', '%s') AND id='%s'", newpw, id, pw, id, id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

}



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con




------------------------------------------------

상담 게시판 회원 정보 수정 (사용자)



//memberInfo.jsp -> [회원정보수정] 메뉴에 링크 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();

String[] array = {"관리자", "직원", "학생", "회원가입"};

String grade = array[dto.getGrade()-1];

%>        

<!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() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle"><%=id%></td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle"><%=name%></td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle"><%=email%></td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle"><%=tel%></td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle"><%=grade%></td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자, 직원 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1' || sessionScope.grade == '2'}">

<a href="memberList.mem">[*회원명단]</a>

</c:if>


<a href="memberPWModifyForm.mem">[패스워드변경]</a>

<a href="memberModifyForm.mem">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>






//MemberServlet.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;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

if (uri.indexOf("memberList.mem") != -1) {

memberList(req,resp);

}

if (uri.indexOf("adminUpdateForm.mem") != -1) {

adminUpdateForm(req,resp);

}

if (uri.indexOf("adminUpdate.mem") != -1) {

adminUpdate(req,resp);

}

if (uri.indexOf("memberPWModifyForm.mem") != -1) {

memberPWModifyForm(req,resp);

}

if (uri.indexOf("memberPWModify.mem") != -1) {

memberPWModify(req,resp);

}

if (uri.indexOf("memberModifyForm.mem") != -1) {

memberModifyForm(req,resp);

}

if (uri.indexOf("memberModify.mem") != -1) {

memberModify(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

//로그인 상태 확인 부분 추가

if (session.getAttribute("id") == null) {

resp.sendRedirect("login.mem");

}

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}


private void memberList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자, 직원만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1

&& (Integer)session.getAttribute("grade") != 2) {

resp.sendRedirect("login.mem");

}

//----------------------------------

//등급별 회원 명단 출력 부분 추가

String grade = req.getParameter("grade");

if (grade == null) {

grade = "0";

}

//등급별로 쿼리의 다른 조건식 생성

String wheres = "";

if (!grade.equals("0")) {

wheres = String.format("WHERE grade=%s", grade);

}

//----------------------------------

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

//----------------------------------

//등급별 출력 이전 쿼리

//arrayList = dao.lists();

//등급별 출력 이후 쿼리

arrayList = dao.lists(wheres);

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberList.jsp");

dispatcher.forward(req, resp);

}


private void adminUpdateForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//아이디 수신

//해당 아이디에 대한 개인정보(MemberDTO) 읽어오기

//수정 페이지에 전송 준비

//수정 페이지(adminUpdateForm.jsp)로 이동

String id = req.getParameter("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("adminUpdateForm.jsp");

dispatcher.forward(req, resp);

}

private void adminUpdate(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//데이터 수신

//UPDATE 쿼리 메소드(adminModify(MemberDTO dto)) 호출

//memberList.con으로 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

String grade = req.getParameter("grade");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dto.setGrade(Integer.parseInt(grade));

dao.adminModify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("memberList.mem");

resp.sendRedirect(url);

}


private void memberPWModifyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberPWModifyForm.jsp");

dispatcher.forward(req, resp);

}


private void memberPWModify(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pw = req.getParameter("pw");

String newpw = req.getParameter("newpw");

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

int result = 0;

try {

dao.connect();

result = dao.pwModify(id, pw, newpw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (result == 1) {

//정보 페이지로 이동

String url = String.format("memberInfo.mem");

resp.sendRedirect(url);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberPWModifyForm.jsp");

dispatcher.forward(req, resp);

}

}


private void memberModifyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인 상태 확인

HttpSession session = req.getSession();

if (session.getAttribute("id") == null) {

resp.sendRedirect("login.mem");

}

//아이디 확보 -> 세션에서 얻는다.

//해당 아이디에 대한 개인정보(MemberDTO) 읽어오기

//수정 페이지에 전송 준비

//수정 페이지(memberModifyForm.jsp)로 이동

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberModifyForm.jsp");

dispatcher.forward(req, resp);

}

private void memberModify(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인 상태 확인

HttpSession session = req.getSession();

if (session.getAttribute("id") == null) {

resp.sendRedirect("login.mem");

}


//데이터 수신

//UPDATE 쿼리 메소드(memberModify(MemberDTO dto)) 호출

//memberInfo.mem으로 이동

req.setCharacterEncoding("euc-kr");

String id = (String)session.getAttribute("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

MemberDAO dao = new MemberDAO();

MemberDTO dto = new MemberDTO();

int result = 0;

try {

dao.connect();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

result = dao.memberModify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (result == 1) {

//정보 페이지로 이동

String url = String.format("memberInfo.mem");

resp.sendRedirect(url);

} else {

req.setAttribute("error", "true");

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberModifyForm.jsp");

dispatcher.forward(req, resp);

}


}



}





//memberModifyForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();


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>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보_회원정보수정]</h3>

<form action="memberModify.mem" method="post" id="memberModifyForm">

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="200px">아이디</td>

<td class="bTitle"><%=id%></td>

</tr>

<tr>

<td class="tName" width="200px">*패스워드<span style="font-size:9pt;">(기존 패스워드 재입력)</span></td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg" style="color:red; font-size:10pt; display:none; ">1~20자 이내 패스워드를 입력해야 합니다.</span></td>

</tr>

<tr>

<td class="tName" width="200px">*이름<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="name" name="name" value="<%=name%>"><span id="nameMsg" style="color:red; font-size:10pt; display:none; ">1~20자 이내 이름을 입력해야 합니다.</span></td>

</tr>

<tr>

<td class="tName" width="200px">*이메일<span style="font-size:9pt;">(100자 이내)</span></td>

<td class="bTitle"><input type="text" id="email" name="email" style="width:300px" value="<%=email%>"><span id="emailMsg" style="color:red; font-size:10pt; display:none; ">1~100자 이내 이메일을 입력해야 합니다.</span></td>

</tr>

<tr>

<td class="tName" width="200px">*전화<span style="font-size:9pt;">(30자 이내)</span></td>

<td class="bTitle"><input type="text" id="tel" name="tel" style="width:300px" value="<%=tel%>"><span id="telMsg" style="color:red; font-size:10pt; display:none; ">1~30자 이내 전화를 입력해야 합니다.</span></td>

</tr>

</table>

<br>

<a href="javascript:memberModifyFormSubmit()">[확인]</a>

<a href="memberInfo.mem">[회원정보]</a>

</form>

</div>

</div>


</body>

</html>






//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.con?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

obj.submit();

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.jsp";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------




function memberPwFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberPwForm");


var pw = document.getElementById("pw");

var newpw = document.getElementById("newpw");

var pwMsg = document.getElementById("pwMsg");

var newpwMsg = document.getElementById("newpwMsg");

pwMsg.style.display = "none";

newpwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (newpw.value == "" || newpw.value.length > 20) {

newpwMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}



function memberModifyFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberModifyForm");


var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

//데이터 전송

obj.submit();

}





//MemberDAO.java

package com.test;


import java.sql.*;

import java.util.ArrayList;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<MemberDTO> lists() 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember ORDER BY grade ASC, name ASC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<MemberDTO> lists(String wheres) 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember %s ORDER BY grade ASC, name ASC", wheres);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int adminModify(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET name='%s', email='%s', tel='%s', grade=%d WHERE id='%s'", dto.getName(), dto.getEmail(), dto.getTel(), dto.getGrade(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int pwModify(String id, String pw, String newpw)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET pw=encrypt('%s', '%s') WHERE pw=encrypt('%s', '%s') AND id='%s'", newpw, id, pw, id, id);

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public int memberModify(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET name='%s', email='%s', tel='%s' WHERE pw=encrypt('%s', '%s') AND id='%s'", dto.getName(), dto.getEmail(), dto.getTel(), dto.getPw(), dto.getId(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

}



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con



-------------------------------------------------

상담 게시판 회원 정보 수정 (사용자) 까지 완성됨.





-------------------------------------------------

JSTL & EL


1. JSTL(JSP Standard Tag Library), EL(Expreession Language)


2. JSTL은 사용자 정의 태그를 표준화 시킨 것. JSP 내부에서 JSP 명령을 태그 스타일의 명령으로 표현한 것.


3. jstl.jar, standard.jar 파일 필요.


4. JSTL은 core, format, xml, sql 처리 영역이 있다.

 - core 영역은 변수 처리, 흐름제어, url 처리등을 담당.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core">


<c:out value="데이터" /> -> 데이터 출력문


<c:set var="변수이름" value="데이터" /> -> 변수 선언문


<c:if test="조건식"> -> if제어문

//실행문

</c:if>


<c:choose> -> if~else제어문

<c:when test="조건식"> </c:when>

<c:otherwise> </c:otherwise>

</c:choose>


<c:forEach var="변수이름" items="컬렉션데이터">

</c:forEach>


5. EL은 표현식(<%=%>)을 대신하는 효과를 가지며 null 값을 가지는 변수에 대해 좀 더 관대하고, 데이터 형 변환을 자동적으로 해준다.


6. EL은 ${표현식} 형태로 표기.

<=%10%>

-> ELK표기법으로 고치면

${dto.id}


WRITTEN BY
빨강꼬마

,

----------------------------------

상담게시판 회원 가입 (아이디 중복 체크)



//memberInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!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="ajaxUtil.js"></script>

<script type="text/javascript" src="consultation.js"></script>


<script type="text/javascript">

function msg() {


}

</script>


</head>

<body onload="msg()">

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[회원가입]</h3>

<form action="memberInsert.mem" method="post" id="memberForm">

* 등록된 전화로 통화가 가능한 경우에만 회원 가입이 완료됩니다.<br>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="200px">*아이디<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="id" name="id"><a href="javascript:idCheck()">[아이디 중복확인]</a><span id="idMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*패스워드<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*이름<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="name" name="name"><span id="nameMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*이메일<span style="font-size:9pt;">(100자 이내)</span></td>

<td class="bTitle"><input type="text" id="email" name="email" style="width:300px"><span id="emailMsg"></span></td>

</tr>

<tr>

<td class="tName" width="200px">*전화<span style="font-size:9pt;">(30자 이내)</span></td>

<td class="bTitle"><input type="text" id="tel" name="tel" style="width:300px"><span id="telMsg"></span></td>

</tr>

</table>

<br>

<a href="javascript:memberFormSubmit()">[확인]</a>

<span id="submitMsg"></span>

</form>

</div>

</div>


</body>

</html>






//MemberServlet.java

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

}





//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.con?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.jsp";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------





//memberIDCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="com.test.*" %>    

<%

String data

= request.getParameter("data");

String result = "OK";

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = dao.searchId(data);

if (dto != null) {

result = "Cancel";

}

}catch(Exception e){

System.out.println(e.toString());

}finally{

dao.close();

}


out.write(result);

%>





문제) 회원 가입의 나머지 절차는 각자 작성할 것.


//consultation.js -> 데이터 검사 및 전송 과정 추가

//MemberServlet.java -> memberInsert.mem, memberInsertOK.mem 서블릿 주소 등록 및 액션 추가

//MemberDAO.java -> add(MemberDTO dto) 메소드 추가

//memberInsertOK.jsp -> 회원 가입 완료 메시지 페이지 작성



//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.con?sid="+sid;

}

}

//---------------------------------



//-------------------------------

//회원 입력 관련 함수 추가


//아이디 중복 검사 확인용 변수 추가

var idCheckClick = false;

var idCheckResult = false;


function idCheck() {

var id = document.getElementById("id");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

/*

idMsg.style.color = "red";

idMsg.style.fontSize = "small";

idMsg.innerHTML = "1~20자 이내의 아이디를 입력해야 합니다.";

*/

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

//Ajax 요청

ajaxFunc(id.value);

idCheckClick = true;

}


function memberFormSubmit() {

//데이터 검사

var obj = document.getElementById("memberForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var name = document.getElementById("name");

var email = document.getElementById("email");

var tel = document.getElementById("tel");

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (id.value == "" || id.value.length > 20) {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">1~20자 이내의 아이디를 입력해야 합니다.</span>";

return;

}

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

var emailMsg = document.getElementById("emailMsg");

emailMsg.style.display = "none";

if (email.value == "" || email.value.length > 100) {

emailMsg.style.display = "inline";

return;

}

var telMsg = document.getElementById("telMsg");

telMsg.style.display = "none";

if (tel.value == "" || tel.value.length > 100) {

telMsg.style.display = "inline";

return;

}

var submitMsg = document.getElementById("submitMsg");

submitMsg.innerHTML = "";

//아이디 중복 검사 여부 확인

if (!idCheckClick) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">아이디 중복 검사를 먼저 해야 합니다.</span>";

return;

} else {

if (!idCheckResult) {

submitMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디이므로 다른 아이디를 사용해야 합니다.</span>";

return;

}

}

//데이터 전송

obj.submit();

}


//Ajax 관련 함수

var xmlReq;

function ajaxFunc(id) {

xmlReq = new XMLHttpRequest(); //IE7.0 이상

var url = "memberIDCheck.jsp";

var postString = "data="+id;

xmlReq.onreadystatechange = callBack;

xmlReq.open("POST", url, true);

xmlReq.setRequestHeader("Content-Type"

, "application/x-www-form-urlencoded; charset=euc-kr");

xmlReq.send(postString);

}


function callBack() {

if (xmlReq.readyState == 4) {

if (xmlReq.status == 200) {

printData();

}

}

}


function printData() {

var result = xmlReq.responseText;

var idMsg = document.getElementById("idMsg");

idMsg.innerHTML = "";

if (result.indexOf("OK") != -1) {

idMsg.innerHTML = "<span style=\"color:blue; font-size:10pt;\">사용 가능한 아이디입니다.</span>";

idCheckResult = true;

} else {

idMsg.innerHTML = "<span style=\"color:red; font-size:10pt;\">사용 불가능한 아이디입니다.</span>";

idCheckResult = false;

}

}


//--------------------------------





//MemberServlet.java

package com.test;


import java.io.IOException;

import java.sql.SQLException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}

}





//MemberDAO.java

package com.test;


import java.sql.*;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

}





//memberInsertOK.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!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>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div style="width:500px;">

<h3>[회원가입]</h3>

<h2>회원 가입이 완료되었습니다.</h2>

<a href="login.mem">[로그인 페이지로 이동]</a>

</div>

</div>


</body>

</html>




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con




---------------------------------------------------

상담 게시판 회원 명단 (관리자, 직원 전용)



//memberInfo.jsp -> 관리자 전용 [*회원명단] 메뉴 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();

String[] array = {"관리자", "직원", "학생", "회원가입"};

String grade = array[dto.getGrade()-1];

%>        

<!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() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle"><%=id%></td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle"><%=name%></td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle"><%=email%></td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle"><%=tel%></td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle"><%=grade%></td>

</tr>

</table>

</div>

<div>

<br>


<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="memberList.mem">[*회원명단]</a>

</c:if>


<a href="">[패스워드변경]</a>

<a href="">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>





//MemberServlet.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;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

if (uri.indexOf("memberList.mem") != -1) {

memberList(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}


private void memberList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

MemberDAO dao = new MemberDAO();

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("memberList.jsp");

dispatcher.forward(req, resp);

}


}





//MemberDAO.java

package com.test;


import java.sql.*;

import java.util.ArrayList;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<MemberDTO> lists() 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember ORDER BY grade ASC, name ASC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

}





//memberList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};


@SuppressWarnings("unchecked")

ArrayList<MemberDTO> arrayList

= (ArrayList<MemberDTO>)request.getAttribute("arrayList");

StringBuilder str = new StringBuilder();

for (MemberDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getId()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getEmail()));

str.append(String.format("<td class=\"bDot\">%s</td>", array[dto.getGrade()-1]));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}


%>    

<!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 memberAdminRemove(url, uid) {

if (confirm("아이디 : "+uid+"\n\n선택한 회원의 정보를 삭제하시겠습니까?")) {

window.location.href=url+"?uid="+uid;

}

}

</script>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="tName" width="100">아이디</td>

<td class="tName">이름</td>

<td class="tName" width="160">전화</td>

<td class="tName" width="160">이메일</td>

<td class="tName" width="80">등급</td>

<td class="tName" width="120">가입일</td>

<td class="tName" width="80"></td>

</tr>

<!-- <tr>

<td class="bDot">admin</td>

<td class="bDot">관리자</td>

<td class="bDot"></td>

<td class="bDot"></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-15</td>

<td class="bDot" style="font-size:9pt;"><a href="">[등급변경]</a><br><a href="">[회원삭제]</a></td>

</tr> -->

<%=str%>

</table>

</div>

</div>


</body>

</html>





--------------------------------------------------

문제) 상담 게시판에서 회원 명단 출력시 등급별(전체, 관리자, 직원, 학생, 회원가입)로 출력되도록 할 것.




//memberList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};


//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

String grade = request.getParameter("grade");

if (grade == null) {

grade = "0";

}

//----------------------------


@SuppressWarnings("unchecked")

ArrayList<MemberDTO> arrayList

= (ArrayList<MemberDTO>)request.getAttribute("arrayList");

StringBuilder str = new StringBuilder();

for (MemberDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getId()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getEmail()));

str.append(String.format("<td class=\"bDot\">%s</td>", array[dto.getGrade()-1]));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}


%>    

<!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 memberAdminRemove(url, uid) {

if (confirm("아이디 : "+uid+"\n\n선택한 회원의 정보를 삭제하시겠습니까?")) {

window.location.href=url+"?uid="+uid;

}

}

function memberList(obj) {

window.location.href="memberList.mem?grade="+obj.value;

}

//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

function radioCheck() {

var radios = document.getElementsByName("radioGroup");

radios[<%=grade%>].checked = true;

}

//----------------------------

</script>


</head>

<body onload="radioCheck()">

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단]</h3>

<div>

<form>

<input type="radio" name="radioGroup" 

checked="checked" 

onclick="memberList(this)" value="0">전체

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="1">관리자

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="2">직원

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="3">학생

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="4">회원가입

</form>

<br>

</div>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="tName" width="100">아이디</td>

<td class="tName">이름</td>

<td class="tName" width="160">전화</td>

<td class="tName" width="160">이메일</td>

<td class="tName" width="80">등급</td>

<td class="tName" width="120">가입일</td>

<td class="tName" width="80"></td>

</tr>

<!-- <tr>

<td class="bDot">admin</td>

<td class="bDot">관리자</td>

<td class="bDot"></td>

<td class="bDot"></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-15</td>

<td class="bDot" style="font-size:9pt;"><a href="">[등급변경]</a><br><a href="">[회원삭제]</a></td>

</tr> -->

<%=str%>

</table>

</div>

</div>


</body>

</html>




//MemberServlet.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;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

if (uri.indexOf("memberList.mem") != -1) {

memberList(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}


private void memberList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//----------------------------------

//등급별 회원 명단 출력 부분 추가

String grade = req.getParameter("grade");

if (grade == null) {

grade = "0";

}

//등급별로 쿼리의 다른 조건식 생성

String wheres = "";

if (!grade.equals("0")) {

wheres = String.format("WHERE grade=%s", grade);

}

//----------------------------------

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

//----------------------------------

//등급별 출력 이전 쿼리

//arrayList = dao.lists();

//등급별 출력 이후 쿼리

arrayList = dao.lists(wheres);

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberList.jsp");

dispatcher.forward(req, resp);

}


}





//MemberDAO.java

package com.test;


import java.sql.*;

import java.util.ArrayList;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<MemberDTO> lists() 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember ORDER BY grade ASC, name ASC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<MemberDTO> lists(String wheres) 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember %s ORDER BY grade ASC, name ASC", wheres);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

}




--------------------------------------------------

상담 게시판에서 회원 수정(관리자 전용)



//memberList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>

<%

String[] array = {"관리자", "직원", "학생", "회원가입"};


//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

String grade = request.getParameter("grade");

if (grade == null) {

grade = "0";

}

//----------------------------


@SuppressWarnings("unchecked")

ArrayList<MemberDTO> arrayList

= (ArrayList<MemberDTO>)request.getAttribute("arrayList");

StringBuilder str = new StringBuilder();

for (MemberDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getId()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getTel()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getEmail()));

str.append(String.format("<td class=\"bDot\">%s</td>", array[dto.getGrade()-1]));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));


//---------------------------

//회원 수정 메뉴 추가(관리자 전용)

str.append(String.format("<td class=\"bDot\">"));

if ((Integer)session.getAttribute("grade") == 1) {

str.append(String.format("<a href=\"adminUpdateForm.mem?id=%s\">[회원수정]</a>", dto.getId()));

}

str.append(String.format("</td>"));

//---------------------------

str.append("</tr>");

}


%>    

<!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 memberAdminRemove(url, uid) {

if (confirm("아이디 : "+uid+"\n\n선택한 회원의 정보를 삭제하시겠습니까?")) {

window.location.href=url+"?uid="+uid;

}

}

function memberList(obj) {

window.location.href="memberList.mem?grade="+obj.value;

}

//----------------------------

//등급별 출력시 선택한 등급 표시하기 위한 부분 추가

function radioCheck() {

var radios = document.getElementsByName("radioGroup");

radios[<%=grade%>].checked = true;

}

//----------------------------

</script>


</head>

<body onload="radioCheck()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단]</h3>

<div>

<form>

<input type="radio" name="radioGroup" 

checked="checked" 

onclick="memberList(this)" value="0">전체

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="1">관리자

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="2">직원

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="3">학생

<input type="radio" name="radioGroup" 

onclick="memberList(this)" value="4">회원가입

</form>

<br>

</div>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="tName" width="100">아이디</td>

<td class="tName">이름</td>

<td class="tName" width="160">전화</td>

<td class="tName" width="160">이메일</td>

<td class="tName" width="80">등급</td>

<td class="tName" width="120">가입일</td>

<td class="tName" width="80"></td>

</tr>

<!-- <tr>

<td class="bDot">admin</td>

<td class="bDot">관리자</td>

<td class="bDot"></td>

<td class="bDot"></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-15</td>

<td class="bDot" style="font-size:9pt;"><a href="">[등급변경]</a><br><a href="">[회원삭제]</a></td>

</tr> -->

<%=str%>

</table>

</div>

</div>


</body>

</html>





//MemberServlet.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;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

if (uri.indexOf("memberInsertForm.mem") != -1) {

memberInsertForm(req,resp);

}

if (uri.indexOf("memberInsert.mem") != -1) {

memberInsert(req,resp);

}

if (uri.indexOf("memberInsertOK.mem") != -1) {

memberInsertOK(req,resp);

}

if (uri.indexOf("memberInsertCancel.mem") != -1) {

memberInsertCancel(req,resp);

}

if (uri.indexOf("memberList.mem") != -1) {

memberList(req,resp);

}

if (uri.indexOf("adminUpdateForm.mem") != -1) {

adminUpdateForm(req,resp);

}

if (uri.indexOf("adminUpdate.mem") != -1) {

adminUpdate(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


private void memberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//memberInsertOK.con으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String pw = req.getParameter("pw");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

id = id.replaceAll("'", "''");

pw = pw.replaceAll("'", "''");

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

boolean idCheck = false;

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setPw(pw);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dao.add(dto);

//데이터베이스 입력시 다시 한 번 아이디 중복 체크 추가

idCheck = true;

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

if (idCheck) {

String url = String.format("memberInsertOK.mem");

resp.sendRedirect(url);

} else {

String url = String.format("memberInsertCancel.mem");

resp.sendRedirect(url);

}

}


private void memberInsertOK(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertOK.jsp");

dispatcher.forward(req, resp);

}

private void memberInsertCancel(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInsertCancel.jsp");

dispatcher.forward(req, resp);

}


private void memberList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자, 직원만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1

&& (Integer)session.getAttribute("grade") != 2) {

resp.sendRedirect("login.mem");

}

//----------------------------------

//등급별 회원 명단 출력 부분 추가

String grade = req.getParameter("grade");

if (grade == null) {

grade = "0";

}

//등급별로 쿼리의 다른 조건식 생성

String wheres = "";

if (!grade.equals("0")) {

wheres = String.format("WHERE grade=%s", grade);

}

//----------------------------------

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

//----------------------------------

//등급별 출력 이전 쿼리

//arrayList = dao.lists();

//등급별 출력 이후 쿼리

arrayList = dao.lists(wheres);

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberList.jsp");

dispatcher.forward(req, resp);

}


private void adminUpdateForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//아이디 수신

//해당 아이디에 대한 개인정보(MemberDTO) 읽어오기

//수정 페이지에 전송 준비

//수정 페이지(adminUpdateForm.jsp)로 이동

String id = req.getParameter("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("adminUpdateForm.jsp");

dispatcher.forward(req, resp);

}

private void adminUpdate(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//관리자만 접근 가능

HttpSession session = req.getSession();

if ((Integer)session.getAttribute("grade") != 1) {

resp.sendRedirect("login.mem");

}

//데이터 수신

//UPDATE 쿼리 메소드(adminModify(MemberDTO dto)) 호출

//memberList.con으로 이동

req.setCharacterEncoding("euc-kr");

String id = req.getParameter("id");

String name = req.getParameter("name");

String email = req.getParameter("email");

String tel = req.getParameter("tel");

String grade = req.getParameter("grade");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

email = email.replaceAll("'", "''");

tel = tel.replaceAll("'", "''");

//-----------------------------

MemberDAO dao = new MemberDAO();

try {

dao.connect();

MemberDTO dto = new MemberDTO();

dto.setId(id);

dto.setName(name);

dto.setEmail(email);

dto.setTel(tel);

dto.setGrade(Integer.parseInt(grade));

dao.adminModify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("memberList.mem");

resp.sendRedirect(url);

}

}





//adminUpdateForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();

int gradeIndex = dto.getGrade();

String[] array = {"관리자", "직원", "학생", "회원가입"};

String grade = array[dto.getGrade()-1];

%>

<!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 adminUpdateFormSubmit() {

var adminUpdateForm = document.getElementById("adminUpdateForm");

adminUpdateForm.submit();

}

function radioCheck() {

var radios = document.getElementsByName("grade");

radios[<%=gradeIndex-1%>].checked = true;

}

</script>


</head>

<body onload="radioCheck()">

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[*회원명단_회원수정]</h3>

<form action="adminUpdate.mem" method="post" id="adminUpdateForm">

<input type="hidden" name="id" value="<%=id%>">

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td class="tName" width="250px">아이디</td>

<td class="bTitle"><%=id%></td>

</tr>

<tr>

<td class="tName" width="250px">이름<span style="font-size:9pt;">(20자 이내)</span></td>

<td class="bTitle"><input type="text" id="name" name="name" value="<%=name%>"></td>

</tr>

<tr>

<td class="tName" width="250px">이메일<span style="font-size:9pt;">(100자 이내)</span></td>

<td class="bTitle"><input type="text" id="email" name="email" style="width:300px" value="<%=email%>"></td>

</tr>

<tr>

<td class="tName" width="250px">전화<span style="font-size:9pt;">(30자 이내)</span></td>

<td class="bTitle"><input type="text" id="tel" name="tel" style="width:300px" value="<%=tel%>"></td>

</tr>

<tr>

<td class="tName" width="250px">등급(<%=grade%>)</td>

<td class="bTitle">

<input type="radio" name="grade" value="1">관리자

<input type="radio" name="grade" value="2">직원

<input type="radio" name="grade" value="3">학생

<input type="radio" name="grade" value="4">회원가입

</td>

</tr>

</table>

<br><br>

<a href="javascript:adminUpdateFormSubmit()">[회원수정]</a>

<a href="memberList.mem">[회원명단]</a>

</form>

</div>

</div>


</body>

</html>





//MemberDAO.java

package com.test;


import java.sql.*;

import java.util.ArrayList;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public int add(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO jmember (id, pw, name, email, tel, wdate) VALUES ('%s', encrypt('%s', '%s'),'%s', '%s', '%s', SYSDATE)", dto.getId(), dto.getPw(), dto.getId(), dto.getName(), dto.getEmail(), dto.getTel());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

public ArrayList<MemberDTO> lists() 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember ORDER BY grade ASC, name ASC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public ArrayList<MemberDTO> lists(String wheres) 

throws SQLException {

ArrayList<MemberDTO> arrayList

= new ArrayList<MemberDTO>();

String sql = String.format("SELECT id, name, tel, email, grade, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate FROM jmember %s ORDER BY grade ASC, name ASC", wheres);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

MemberDTO dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTel(rs.getString("tel"));

dto.setEmail(rs.getString("email"));

dto.setGrade(rs.getInt("grade"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int adminModify(MemberDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("UPDATE jmember SET name='%s', email='%s', tel='%s', grade=%d WHERE id='%s'", dto.getName(), dto.getEmail(), dto.getTel(), dto.getGrade(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

}




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


-----------------------------------------------

상담 게시판 회원 수정(관리자 전용) 까지 작성됨.


WRITTEN BY
빨강꼬마

,

----------------------------------------

상담 게시판 댓글 쓰기 (로그인한 사용자만 댓글 쓰기 가능)


//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ 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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


//-----------------------------------

//답변글 출력 준비 추가

ConsultationDTO rdto 

= (ConsultationDTO)request.getAttribute("rdto");

String rname = "";

String rtitle = "";

String rwdate = "";

String rcontent = "";

if (rdto != null) {

rname = rdto.getName();

rtitle = rdto.getTitle();

rwdate = rdto.getWdate();

rcontent = rdto.getContent();

rname = rname.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rtitle = rtitle.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("  ", "&nbsp;");

rcontent = rcontent.replaceAll("\n", "<br>");

rcontent = rcontent.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

}


//----------------------------------


%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<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%>

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><%=rtitle%></h3>

<span><%=rname%></span>

<span><%=rwdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<%=rcontent%>

</td>

</tr>

</table>

</div>

</c:if>

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 1 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.con" method="post" id="commentInsertForm">

<input type="hidden" name="sid" value="<%=sid%>">

글쓴이 '<%=(String)session.getAttribute("name")%>' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

</tr>

<tr>

<td>박길동</td>

<td>참고합니다.</td>

<td>2012-03-16</td>

</tr>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.con?sid=<%=sid%>">[*답변글쓰기]</a>

</c:if>

<a href="consultList.con">[목록보기]</a>

<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>




//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}





//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;

import javax.servlet.http.HttpSession;


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);

}

if (uri.indexOf("consultSearch.con") != -1) {

consultSearch(req, resp);

}

if (uri.indexOf("adminReplyForm.con") != -1) {

adminReplyForm(req, resp);

}

if (uri.indexOf("adminReply.con") != -1) {

adminReply(req, resp);

}

if (uri.indexOf("commentInsert.con") != -1) {

commentInsert(req, resp);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

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 {

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String title = req.getParameter("title");

String content = req.getParameter("content");


ConsultationDAO dao = new ConsultationDAO();


try{

dao.connect();


ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setTitle(title);

dto.setContent(content);


dao.modify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try{

dao.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

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);

}

}

}


private void consultSearch(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//한글 인코딩 처리

//데이터 수신(skey, svalue)

//검색 실행 -> searchLists(skey, svalue)

//검색 결과(ArrayList<ConsultationDTO>)를 

//출력 페이지(consultList.jsp)로 전달

req.setCharacterEncoding("euc-kr");

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");


ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

arrayList = dao.searchLists(skey, svalue);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultList.jsp");

dispatcher.forward(req, resp);

}


private void adminReplyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//데이터베이스 연결

//글번호에 해당하는 글 정보 읽어온다.

//글 정보(ConsultationDTO)를 출력 페이지로 전달

//답변 글쓰기 페이지(adminReplyForm.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("adminReplyForm.jsp");

dispatcher.forward(req, resp);

}


private void adminReply(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String name = req.getParameter("name");

String title = req.getParameter("title");

String content = req.getParameter("content");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

title = title.replaceAll("'", "''");

content = content.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setName(name);

dto.setTitle(title);

dto.setContent(content);

dao.adminReply(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 commentInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultView.con 으로 페이지 이동

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

String title = req.getParameter("title");

String sid = req.getParameter("sid");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

title = title.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setId(id);

dto.setName(name);

dto.setTitle(title);

dto.setSid(sid);

dao.commentAdd(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

}





//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


//-----------------------------

//답변글 읽어오는 전용 변수 추가

private String rid;

public String getRid() {

return rid;

}


public void setRid(String rid) {

this.rid = rid;

}

//-----------------------------

//-------------------------------

//댓글 처리를 위한 id 변수 추가

private String id;

public String getId() {

return id;

}


public void setId(String id) {

this.id = id;

}

//-------------------------------



public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


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 String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}





//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, rid 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"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

}

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 modify(ConsultationDTO dto) throws SQLException {

int result =0;


String sql = String.format("UPDATE consultation SET title='%s', CONTENT='%s', wdate=SYSDATE WHERE SID=%s"

, dto.getTitle()

, dto.getContent()

, dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

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;

}



//상담 게시판 글검색 출력

public ArrayList<ConsultationDTO> searchLists(String skey, String svalue) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, rid FROM consultation WHERE LOWER(%s) LIKE '%%'||LOWER('%s')||'%%' ORDER BY sid DESC", skey, svalue);

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"));

//답변글 번호 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


//-------------------------------------------

//페이지 처리 후 

//상담 게시판 글목록 출력 (페이지 처리 후, 답변글 처리 후)

public ArrayList<ConsultationDTO> lists(int start, int end) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT * FROM pageListView WHERE rnum>=%d AND rnum<=%d", start, end);

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"));

//답변글 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM consultation");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

//-------------------------------------------


public int adminReply(ConsultationDTO dto)

throws SQLException {

int result = 0;


//답변글 쓰기

String sql = String.format("INSERT INTO consultReply (rid, name, title, content, wdate) VALUES (consultReplySeq.nextval, '%s', '%s','%s', SYSDATE)", dto.getName(), dto.getTitle(), dto.getContent());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 답변글 연결 지정

String sql2 = String.format("UPDATE consultation SET rid=consultReplySeq.currval WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//답변글 읽어오는 전용 메소드 추가

public ConsultationDTO searchByRid(String rid) 

throws SQLException {

ConsultationDTO dto = new ConsultationDTO();


String sql = String.format("SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultReply WHERE rid=%s", rid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto.setRid(rs.getString("rid"));

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 int commentAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

//댓글 쓰기

String sql = String.format("INSERT INTO consultComment (cid, id, name, title, wdate, sid) VALUES (consultCommentSeq.nextval, '%s', '%s', '%s', SYSDATE, %s)", dto.getId(), dto.getName(), dto.getTitle(), dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 댓글 갯수 증가

String sql2 = String.format("UPDATE consultation SET commentCount = commentCount + 1 WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

}





--------------------------------------------------------

상담 게시판 댓글 출력



//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


//-----------------------------

//답변글 읽어오는 전용 변수 추가

private String rid;

public String getRid() {

return rid;

}


public void setRid(String rid) {

this.rid = rid;

}

//-----------------------------

//-------------------------------

//댓글 처리를 위한 id 변수 추가

private String id;

public String getId() {

return id;

}


public void setId(String id) {

this.id = id;

}


//댓글 처리를 위한 commentCount 변수 추가

private int commentCount;

public int getCommentCount() {

return commentCount;

}


public void setCommentCount(int commentCount) {

this.commentCount = commentCount;

}

//댓글 처리를 위한 cid 변수 추가

private String cid;

public String getCid() {

return cid;

}

public void setCid(String cid) {

this.cid = cid;

}

//-------------------------------


public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


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 String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}





//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, rid, commentCount 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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

}

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 modify(ConsultationDTO dto) throws SQLException {

int result =0;


String sql = String.format("UPDATE consultation SET title='%s', CONTENT='%s', wdate=SYSDATE WHERE SID=%s"

, dto.getTitle()

, dto.getContent()

, dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

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;

}



//상담 게시판 글검색 출력

public ArrayList<ConsultationDTO> searchLists(String skey, String svalue) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, rid, commentCount FROM consultation WHERE LOWER(%s) LIKE '%%'||LOWER('%s')||'%%' ORDER BY sid DESC", skey, svalue);

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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 번호 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


//-------------------------------------------

//페이지 처리 후 

//상담 게시판 글목록 출력 (페이지 처리 후, 답변글 처리 후, 댓글 처리 후)

public ArrayList<ConsultationDTO> lists(int start, int end) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT * FROM pageListView WHERE rnum>=%d AND rnum<=%d", start, end);

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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM consultation");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

//-------------------------------------------


public int adminReply(ConsultationDTO dto)

throws SQLException {

int result = 0;


//답변글 쓰기

String sql = String.format("INSERT INTO consultReply (rid, name, title, content, wdate) VALUES (consultReplySeq.nextval, '%s', '%s','%s', SYSDATE)", dto.getName(), dto.getTitle(), dto.getContent());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 답변글 연결 지정

String sql2 = String.format("UPDATE consultation SET rid=consultReplySeq.currval WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//답변글 읽어오는 전용 메소드 추가

public ConsultationDTO searchByRid(String rid) 

throws SQLException {

ConsultationDTO dto = new ConsultationDTO();


String sql = String.format("SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultReply WHERE rid=%s", rid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto.setRid(rs.getString("rid"));

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 int commentAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

//댓글 쓰기

String sql = String.format("INSERT INTO consultComment (cid, id, name, title, wdate, sid) VALUES (consultCommentSeq.nextval, '%s', '%s', '%s', SYSDATE, %s)", dto.getId(), dto.getName(), dto.getTitle(), dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 댓글 갯수 증가

String sql2 = String.format("UPDATE consultation SET commentCount = commentCount + 1 WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//--------------------------------

//댓글 목록 읽어오는 전용 메소드 추가

public ArrayList<ConsultationDTO> commentLists(String sid) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT cid, id, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate FROM consultComment WHERE sid=%s ORDER BY cid ASC", sid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

ConsultationDTO dto = new ConsultationDTO();

dto.setCid(rs.getString("cid"));

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTitle(rs.getString("title"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

//---------------------------------

}





//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;

import javax.servlet.http.HttpSession;


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);

}

if (uri.indexOf("consultSearch.con") != -1) {

consultSearch(req, resp);

}

if (uri.indexOf("adminReplyForm.con") != -1) {

adminReplyForm(req, resp);

}

if (uri.indexOf("adminReply.con") != -1) {

adminReply(req, resp);

}

if (uri.indexOf("commentInsert.con") != -1) {

commentInsert(req, resp);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

ArrayList<ConsultationDTO> commentLists

= new ArrayList<ConsultationDTO>();

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

if (dto.getCommentCount() > 0) {

commentLists = dao.commentLists(sid);

}

//----------------------------------


}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

req.setAttribute("commentLists", commentLists);

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 {

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String title = req.getParameter("title");

String content = req.getParameter("content");


ConsultationDAO dao = new ConsultationDAO();


try{

dao.connect();


ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setTitle(title);

dto.setContent(content);


dao.modify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try{

dao.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

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);

}

}

}


private void consultSearch(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//한글 인코딩 처리

//데이터 수신(skey, svalue)

//검색 실행 -> searchLists(skey, svalue)

//검색 결과(ArrayList<ConsultationDTO>)를 

//출력 페이지(consultList.jsp)로 전달

req.setCharacterEncoding("euc-kr");

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");


ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

arrayList = dao.searchLists(skey, svalue);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultList.jsp");

dispatcher.forward(req, resp);

}


private void adminReplyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//데이터베이스 연결

//글번호에 해당하는 글 정보 읽어온다.

//글 정보(ConsultationDTO)를 출력 페이지로 전달

//답변 글쓰기 페이지(adminReplyForm.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("adminReplyForm.jsp");

dispatcher.forward(req, resp);

}


private void adminReply(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String name = req.getParameter("name");

String title = req.getParameter("title");

String content = req.getParameter("content");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

title = title.replaceAll("'", "''");

content = content.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setName(name);

dto.setTitle(title);

dto.setContent(content);

dao.adminReply(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 commentInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultView.con 으로 페이지 이동

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

String title = req.getParameter("title");

String sid = req.getParameter("sid");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

title = title.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setId(id);

dto.setName(name);

dto.setTitle(title);

dto.setSid(sid);

dao.commentAdd(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

}





//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

//검색 기준, 검색 단어 수신

String skey = request.getParameter("skey");

if (skey == null) {

skey = "";

}

String svalue = request.getParameter("svalue");

if (svalue == null) {

svalue = "";

}

//제목 글자 수신

String title = (String)request.getAttribute("title");

//페이징 처리 수신

String pageUrl = (String)request.getAttribute("pageUrl");;

if (pageUrl == null) {

pageUrl = "<br>";

}


@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\"><a href=\"consultView.con?sid=%s\">%s</a>", dto.getSid(), dto.getTitle()));


//댓글 갯수 출력 부분

if (dto.getCommentCount() > 0) {

str.append(String.format("<span style=\"color:red; font-size:10pt;\">[%d]</span>", dto.getCommentCount()));

}

//답변글 출력 부분

if (dto.getRid() != null) {

str.append("<span style=\"color:blue; font-size:10pt;\">[답변있음]</span>");

}

str.append("</td>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}

StringBuilder options = new StringBuilder();

if (skey.equals("title")) {

options.append("<option value=\"title\" selected=\"selected\">제목</option>");

} else {

options.append("<option value=\"title\">제목</option>");

}

if (skey.equals("content")) {

options.append("<option value=\"content\" selected=\"selected\">내용</option>");

} else {

options.append("<option value=\"content\">내용</option>");

}

if (skey.equals("name")) {

options.append("<option value=\"name\" selected=\"selected\">글작성자</option>");

} else {

options.append("<option value=\"name\">글작성자</option>");

}


%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_<%=title%>]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle"><a href="consultView.con?sid=1">상담 게시판이 오픈되었습니다.</a></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot"><%=pageUrl%></td>

</tr>

</table>

<form action="consultSearch.con" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey"><%=options%></select>

<input type="text" id="svalue" name="svalue" value="<%=svalue%>">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<a href="consultInsertForm.con">[새글쓰기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%@ page import="java.util.*" %>

<%

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();

int commentCount = dto.getCommentCount();

//----------------------------------

//출력 오류 처리 필요

//내용에 HTML 태그가 포함된 경우

//HTML 태그가 태그로 보이는게 아니라 실행 코드가 되버린다.

//태그를 문자열로 변경시켜야 한다.

name = name.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


//-----------------------------------

//답변글 출력 준비 추가

ConsultationDTO rdto 

= (ConsultationDTO)request.getAttribute("rdto");

String rname = "";

String rtitle = "";

String rwdate = "";

String rcontent = "";

if (rdto != null) {

rname = rdto.getName();

rtitle = rdto.getTitle();

rwdate = rdto.getWdate();

rcontent = rdto.getContent();

rname = rname.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rtitle = rtitle.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("  ", "&nbsp;");

rcontent = rcontent.replaceAll("\n", "<br>");

rcontent = rcontent.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

}


//----------------------------------

//-----------------------------------

//댓글 목록 출력 준비 추가

@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> commentLists

= (ArrayList<ConsultationDTO>)request.getAttribute("commentLists");

StringBuilder comments = new StringBuilder();

for (ConsultationDTO cdto : commentLists) {

comments.append("<tr>");

comments.append(String.format("<td>%s</td>", cdto.getName()));

comments.append(String.format("<td>%s</td>", cdto.getTitle()));

comments.append(String.format("<td>%s</td>", cdto.getWdate()));

comments.append("</tr>");

}

//-----------------------------------


%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<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%>

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><%=rtitle%></h3>

<span><%=rname%></span>

<span><%=rwdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<%=rcontent%>

</td>

</tr>

</table>

</div>

</c:if>

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 <%=commentCount%> 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.con" method="post" id="commentInsertForm">

<input type="hidden" name="sid" value="<%=sid%>">

글쓴이 '<%=(String)session.getAttribute("name")%>' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

</tr>

<!-- <tr>

<td>박길동</td>

<td>참고합니다.</td>

<td>2012-03-16</td>

</tr> -->

<%=comments%>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.con?sid=<%=sid%>">[*답변글쓰기]</a>

</c:if>

<a href="consultList.con">[목록보기]</a>

<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


--------------------------------------------------------

문제) 상담 게시판 댓글 삭제 (로그인한 사용자가 본인이 쓴 댓글만 삭제 가능)




--------------------------------------------------------

상담 게시판 회원 글쓰기(로그인한 사용자인 경우)


//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

//검색 기준, 검색 단어 수신

String skey = request.getParameter("skey");

if (skey == null) {

skey = "";

}

String svalue = request.getParameter("svalue");

if (svalue == null) {

svalue = "";

}

//제목 글자 수신

String title = (String)request.getAttribute("title");

//페이징 처리 수신

String pageUrl = (String)request.getAttribute("pageUrl");;

if (pageUrl == null) {

pageUrl = "<br>";

}


@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\"><a href=\"consultView.con?sid=%s\">%s</a>", dto.getSid(), dto.getTitle()));


//댓글 갯수 출력 부분

if (dto.getCommentCount() > 0) {

str.append(String.format("<span style=\"color:red; font-size:10pt;\">[%d]</span>", dto.getCommentCount()));

}

//답변글 출력 부분

if (dto.getRid() != null) {

str.append("<span style=\"color:blue; font-size:10pt;\">[답변있음]</span>");

}

str.append("</td>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}

StringBuilder options = new StringBuilder();

if (skey.equals("title")) {

options.append("<option value=\"title\" selected=\"selected\">제목</option>");

} else {

options.append("<option value=\"title\">제목</option>");

}

if (skey.equals("content")) {

options.append("<option value=\"content\" selected=\"selected\">내용</option>");

} else {

options.append("<option value=\"content\">내용</option>");

}

if (skey.equals("name")) {

options.append("<option value=\"name\" selected=\"selected\">글작성자</option>");

} else {

options.append("<option value=\"name\">글작성자</option>");

}


%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_<%=title%>]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle"><a href="consultView.con?sid=1">상담 게시판이 오픈되었습니다.</a></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot"><%=pageUrl%></td>

</tr>

</table>

<form action="consultSearch.con" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey"><%=options%></select>

<input type="text" id="svalue" name="svalue" value="<%=svalue%>">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<%-- 회원 로그인 여부에 따라서 다른 새글쓰기 메뉴 출력됨 --%>

<c:choose>

<c:when test="${empty sessionScope.id}"><a href="consultInsertForm.con">[새글쓰기]</a></c:when>

<c:otherwise><a href="consultMemberInsertForm.con">[새글쓰기]</a></c:otherwise>

</c:choose>

</td>

</tr>

</table>

</form>

</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;

import javax.servlet.http.HttpSession;


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);

}

if (uri.indexOf("consultSearch.con") != -1) {

consultSearch(req, resp);

}

if (uri.indexOf("adminReplyForm.con") != -1) {

adminReplyForm(req, resp);

}

if (uri.indexOf("adminReply.con") != -1) {

adminReply(req, resp);

}

if (uri.indexOf("commentInsert.con") != -1) {

commentInsert(req, resp);

}

if (uri.indexOf("consultMemberInsertForm.con") != -1) {

consultMemberInsertForm(req, resp);

}

if (uri.indexOf("consultMemberInsert.con") != -1) {

consultMemberInsert(req, resp);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

ArrayList<ConsultationDTO> commentLists

= new ArrayList<ConsultationDTO>();

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

if (dto.getCommentCount() > 0) {

commentLists = dao.commentLists(sid);

}

//----------------------------------


}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

req.setAttribute("commentLists", commentLists);

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 {

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String title = req.getParameter("title");

String content = req.getParameter("content");


ConsultationDAO dao = new ConsultationDAO();


try{

dao.connect();


ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setTitle(title);

dto.setContent(content);


dao.modify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try{

dao.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

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);

}

}

}


private void consultSearch(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//한글 인코딩 처리

//데이터 수신(skey, svalue)

//검색 실행 -> searchLists(skey, svalue)

//검색 결과(ArrayList<ConsultationDTO>)를 

//출력 페이지(consultList.jsp)로 전달

req.setCharacterEncoding("euc-kr");

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");


ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

arrayList = dao.searchLists(skey, svalue);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultList.jsp");

dispatcher.forward(req, resp);

}


private void adminReplyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//데이터베이스 연결

//글번호에 해당하는 글 정보 읽어온다.

//글 정보(ConsultationDTO)를 출력 페이지로 전달

//답변 글쓰기 페이지(adminReplyForm.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("adminReplyForm.jsp");

dispatcher.forward(req, resp);

}


private void adminReply(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String name = req.getParameter("name");

String title = req.getParameter("title");

String content = req.getParameter("content");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

title = title.replaceAll("'", "''");

content = content.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setName(name);

dto.setTitle(title);

dto.setContent(content);

dao.adminReply(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 commentInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultView.con 으로 페이지 이동

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

String title = req.getParameter("title");

String sid = req.getParameter("sid");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

title = title.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setId(id);

dto.setName(name);

dto.setTitle(title);

dto.setSid(sid);

dao.commentAdd(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}


private void consultMemberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultMemberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void consultMemberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

//회원 정보를 세션을 이용해서 얻어 온다

//name, pw 를 채운다.

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String name = (String)session.getAttribute("name");

String pw = (String)session.getAttribute("id");

String title = req.getParameter("title");

String content = req.getParameter("content");

String id = (String)session.getAttribute("id");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

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);

dto.setId(id);

dao.memberAdd(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);

}

}






//consultMemberInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_글쓰기]</h3>

<form action="consultMemberInsert.con" method="post" id="consultInsertForm">

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="100">제목*</td>

<td class="bTitle"><input type="text" style="width:600px;" id="title" name="title"><span id="titleMsg" style="color:red; display:none;">1~100자 제목 입력</span></td>

</tr>

<tr>

<td class="tName" width="100">내용</td>

<td class="bTitle"><textarea style="width:600px;height:200px;" id="content" name="content"></textarea></td>

</tr>

</table>

<table>

<tr>

<td>

<a href="javascript:consultMemberInsertSubmit()">[글쓰기]</a>

<a href="javascript:consultInsertReset()">[새로작성]</a>

<a href="consultList.con">[목록보기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}






//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, rid, commentCount 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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

}

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 modify(ConsultationDTO dto) throws SQLException {

int result =0;


String sql = String.format("UPDATE consultation SET title='%s', CONTENT='%s', wdate=SYSDATE WHERE SID=%s"

, dto.getTitle()

, dto.getContent()

, dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

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;

}



//상담 게시판 글검색 출력

public ArrayList<ConsultationDTO> searchLists(String skey, String svalue) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, rid, commentCount FROM consultation WHERE LOWER(%s) LIKE '%%'||LOWER('%s')||'%%' ORDER BY sid DESC", skey, svalue);

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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 번호 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


//-------------------------------------------

//페이지 처리 후 

//상담 게시판 글목록 출력 (페이지 처리 후, 답변글 처리 후, 댓글 처리 후)

public ArrayList<ConsultationDTO> lists(int start, int end) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT * FROM pageListView WHERE rnum>=%d AND rnum<=%d", start, end);

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"));

dto.setCommentCount(rs.getInt("commentCount"));

//답변글 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM consultation");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

//-------------------------------------------


public int adminReply(ConsultationDTO dto)

throws SQLException {

int result = 0;


//답변글 쓰기

String sql = String.format("INSERT INTO consultReply (rid, name, title, content, wdate) VALUES (consultReplySeq.nextval, '%s', '%s','%s', SYSDATE)", dto.getName(), dto.getTitle(), dto.getContent());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 답변글 연결 지정

String sql2 = String.format("UPDATE consultation SET rid=consultReplySeq.currval WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//답변글 읽어오는 전용 메소드 추가

public ConsultationDTO searchByRid(String rid) 

throws SQLException {

ConsultationDTO dto = new ConsultationDTO();


String sql = String.format("SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultReply WHERE rid=%s", rid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto.setRid(rs.getString("rid"));

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 int commentAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

//댓글 쓰기

String sql = String.format("INSERT INTO consultComment (cid, id, name, title, wdate, sid) VALUES (consultCommentSeq.nextval, '%s', '%s', '%s', SYSDATE, %s)", dto.getId(), dto.getName(), dto.getTitle(), dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 댓글 갯수 증가

String sql2 = String.format("UPDATE consultation SET commentCount = commentCount + 1 WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//--------------------------------

//댓글 목록 읽어오는 전용 메소드 추가

public ArrayList<ConsultationDTO> commentLists(String sid) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT cid, id, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate FROM consultComment WHERE sid=%s ORDER BY cid ASC", sid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

ConsultationDTO dto = new ConsultationDTO();

dto.setCid(rs.getString("cid"));

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTitle(rs.getString("title"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

//---------------------------------

//---------------------------------------

//상담 게시판 글 입력 (회원 글쓰기)

public int memberAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO consultation (sid, name, pw, title, content, wdate, id) VALUES (consultationSeq.nextVal,'%s',encrypt('%s', '%s'),'%s','%s',SYSDATE, '%s')", dto.getName(), dto.getPw(), dto.getName(), dto.getTitle(), dto.getContent(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

//---------------------------------------

}





문제) 상담 게시판에서 회원 전용 수정, 삭제 과정 추가할 것.



//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%@ page import="java.util.*" %>

<%

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();

int commentCount = dto.getCommentCount();


//---------------------------------

//회원 전용 수정, 삭제 부분 추가

//데이터베이스에서 회원 아이디 정보를 읽어오는 부분 추가

String id = dto.getId();

if (id == null) {

id = "비회원";

}

//회원 아이디 정보를 EL 표현에서 사용할 수 있도록 추가한 부분

request.setAttribute("id", id);

//---------------------------------

//----------------------------------

//출력 오류 처리 필요

//내용에 HTML 태그가 포함된 경우

//HTML 태그가 태그로 보이는게 아니라 실행 코드가 되버린다.

//태그를 문자열로 변경시켜야 한다.

name = name.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


//-----------------------------------

//답변글 출력 준비 추가

ConsultationDTO rdto 

= (ConsultationDTO)request.getAttribute("rdto");

String rname = "";

String rtitle = "";

String rwdate = "";

String rcontent = "";

if (rdto != null) {

rname = rdto.getName();

rtitle = rdto.getTitle();

rwdate = rdto.getWdate();

rcontent = rdto.getContent();

rname = rname.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rtitle = rtitle.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("  ", "&nbsp;");

rcontent = rcontent.replaceAll("\n", "<br>");

rcontent = rcontent.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

}


//----------------------------------

//-----------------------------------

//댓글 목록 출력 준비 추가

@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> commentLists

= (ArrayList<ConsultationDTO>)request.getAttribute("commentLists");

StringBuilder comments = new StringBuilder();

for (ConsultationDTO cdto : commentLists) {

comments.append("<tr>");

comments.append(String.format("<td>%s</td>", cdto.getName()));

comments.append(String.format("<td>%s</td>", cdto.getTitle()));

comments.append(String.format("<td>%s</td>", cdto.getWdate()));

//댓글에 저장된 아이디와 로그인한 아이디가 같은 경우

//삭제 메뉴 출력

if (session.getAttribute("id") != null

&& cdto.getId().equals((String)session.getAttribute("id"))) {

comments.append("<td><a href=\"\">[삭제]</a></td>");

} else {

comments.append("<td></td>");

}

comments.append("</tr>");

}

//-----------------------------------


%>    

<!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>


</head>

<body>

<div>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<div>

<h3>[상담게시판_내용보기]</h3>

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><!-- 상담 게시판을 오픈합니다. --><%=title%></h3>

<span><!-- 관리자 --><%=name%>(<%=id%>)</span>

<span><!-- 2010-01-01 --><%=wdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<!-- 많은 이용 바랍니다. -->

<%=content%>

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><%=rtitle%></h3>

<span><%=rname%></span>

<span><%=rwdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<%=rcontent%>

</td>

</tr>

</table>

</div>

</c:if>

</td>

</tr>

</table>

<!-- 댓글 부분 추가 -->

<div style="margin-top:10px;font-size:10pt;">

 <%=commentCount%> 개의 댓글이 있습니다. 

 <a href="javascript:commentDivPanel()" id="commentMsg">[댓글 펼치기]</a>

</div>

<div style="margin-top:10px;font-size:10pt;display:none;" id="commentDiv">

<c:if test="${!empty sessionScope.id}">

<!-- 댓글 입력 부분 추가 -->

<form action="commentInsert.con" method="post" id="commentInsertForm">

<input type="hidden" name="sid" value="<%=sid%>">

글쓴이 '<%=(String)session.getAttribute("name")%>' 이름으로

<input type="text" style="width:500px;" id="title" name="title">

(200자 이내)

<a href="javascript:commentInsertSubmit()">[댓글쓰기]</a>

<span id="commentErrMsg" style="color:red; display:none;">1~200자 이내로 입력해야 합니다.</span>

</form>

</c:if>

<table cellpadding="5" class="style01 borderTop" style="font-size:10pt;">

<tr>

<td class="tName" width="120">글쓴이</td>

<td class="tName">댓글내용</td>

<td class="tName" width="120">글쓴날짜</td>

<td class="tName"></td>

</tr>

<!-- <tr>

<td>박길동</td>

<td>참고합니다.</td>

<td>2012-03-16</td>

<td><a href="">[삭제]</a></td>

</tr> -->

<%=comments%>

</table>

</div>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.con?sid=<%=sid%>">[*답변글쓰기]</a>

</c:if>

<a href="consultList.con">[목록보기]</a>


<%-- ------------------------------- --%>

<%-- 회원 전용 수정, 삭제 추가한 부분 --%>

<%-- 회원 로그인한 경우와 비회원인 경우를 구분해서 수정, 삭제 진행 --%>

<c:choose>

<c:when test="${empty sessionScope.id && id == '비회원'}">

<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>

</c:when>

<c:when test="${!empty sessionScope.id && sessionScope.id == id}">

<a href="consultMemberModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="javascript:consultMemberDelete(<%=sid%>)">[글 삭제]</a>

</c:when>

<c:otherwise>

</c:otherwise>

</c:choose>

<%-- ------------------------------- --%>

</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;

import javax.servlet.http.HttpSession;


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);

}

if (uri.indexOf("consultSearch.con") != -1) {

consultSearch(req, resp);

}

if (uri.indexOf("adminReplyForm.con") != -1) {

adminReplyForm(req, resp);

}

if (uri.indexOf("adminReply.con") != -1) {

adminReply(req, resp);

}

if (uri.indexOf("commentInsert.con") != -1) {

commentInsert(req, resp);

}

if (uri.indexOf("consultMemberInsertForm.con") != -1) {

consultMemberInsertForm(req, resp);

}

if (uri.indexOf("consultMemberInsert.con") != -1) {

consultMemberInsert(req, resp);

}

if (uri.indexOf("consultMemberModifyForm.con") != -1) {

consultMemberModifyForm(req, resp);

}

if (uri.indexOf("consultMemberDelete.con") != -1) {

consultMemberDelete(req, resp);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

ArrayList<ConsultationDTO> commentLists

= new ArrayList<ConsultationDTO>();

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

//----------------------------------

//댓글 목록 읽어오는 부분 추가

if (dto.getCommentCount() > 0) {

commentLists = dao.commentLists(sid);

}

//----------------------------------


}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

req.setAttribute("commentLists", commentLists);

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 {

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String title = req.getParameter("title");

String content = req.getParameter("content");


ConsultationDAO dao = new ConsultationDAO();


try{

dao.connect();


ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setTitle(title);

dto.setContent(content);


dao.modify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try{

dao.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}

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);

}

}

}


private void consultSearch(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//한글 인코딩 처리

//데이터 수신(skey, svalue)

//검색 실행 -> searchLists(skey, svalue)

//검색 결과(ArrayList<ConsultationDTO>)를 

//출력 페이지(consultList.jsp)로 전달

req.setCharacterEncoding("euc-kr");

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");


ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

arrayList = dao.searchLists(skey, svalue);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultList.jsp");

dispatcher.forward(req, resp);

}


private void adminReplyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//데이터베이스 연결

//글번호에 해당하는 글 정보 읽어온다.

//글 정보(ConsultationDTO)를 출력 페이지로 전달

//답변 글쓰기 페이지(adminReplyForm.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("adminReplyForm.jsp");

dispatcher.forward(req, resp);

}


private void adminReply(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String name = req.getParameter("name");

String title = req.getParameter("title");

String content = req.getParameter("content");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

title = title.replaceAll("'", "''");

content = content.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setName(name);

dto.setTitle(title);

dto.setContent(content);

dao.adminReply(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 commentInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultView.con 으로 페이지 이동

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String id = (String)session.getAttribute("id");

String name = (String)session.getAttribute("name");

String title = req.getParameter("title");

String sid = req.getParameter("sid");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

title = title.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setId(id);

dto.setName(name);

dto.setTitle(title);

dto.setSid(sid);

dao.commentAdd(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}


private void consultMemberInsertForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultMemberInsertForm.jsp");

dispatcher.forward(req, resp);

}

private void consultMemberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

//회원 정보를 세션을 이용해서 얻어 온다

//name, pw 를 채운다.

HttpSession session = req.getSession();

req.setCharacterEncoding("euc-kr");

String name = (String)session.getAttribute("name");

String pw = (String)session.getAttribute("id");

String title = req.getParameter("title");

String content = req.getParameter("content");

String id = (String)session.getAttribute("id");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

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);

dto.setId(id);

dao.memberAdd(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 consultMemberModifyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//수정 페이지로 이동 -> consultMemberModifyForm.jsp

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

ConsultationDAO dao = new ConsultationDAO();

ConsultationDTO dto = null;

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("consultModifyForm.jsp");

dispatcher.forward(req, resp);

}



//회원 전용 삭제 메소드 추가

private void consultMemberDelete(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//DELETE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

//회원 정보를 세션을 이용해서 얻어 온다

//name, pw 를 채운다.

HttpSession session = req.getSession();

String sid = req.getParameter("sid");

String id = (String)session.getAttribute("id");

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setId(id);

dao.memberRemove(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);

}

//--------------------------------------------


}




//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, rid, commentCount, id 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"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

//댓글 갯수 읽어오는 부분 추가

dto.setCommentCount(rs.getInt("commentCount"));


//회원 전용 글쓰기 처리 부분 추가

dto.setId(rs.getString("id"));


}

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 modify(ConsultationDTO dto) throws SQLException {

int result =0;


String sql = String.format("UPDATE consultation SET title='%s', CONTENT='%s', wdate=SYSDATE WHERE SID=%s"

, dto.getTitle()

, dto.getContent()

, dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}

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;

}



//상담 게시판 글검색 출력

public ArrayList<ConsultationDTO> searchLists(String skey, String svalue) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, rid, commentCount, id FROM consultation WHERE LOWER(%s) LIKE '%%'||LOWER('%s')||'%%' ORDER BY sid DESC", skey, svalue);

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"));

//답변글 번호 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

//댓글 갯수 읽어오는 부분 추가

dto.setCommentCount(rs.getInt("commentCount"));


//회원 전용 글쓰기 처리 부분 추가

dto.setId(rs.getString("id"));


arrayList.add(dto);

}

rs.close();

return arrayList;

}


//-------------------------------------------

//페이지 처리 후 

//상담 게시판 글목록 출력 (페이지 처리 후, 답변글 처리 후, 댓글 처리 후, 회원 전용 글쓰기 처리 후)

public ArrayList<ConsultationDTO> lists(int start, int end) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT * FROM pageListView WHERE rnum>=%d AND rnum<=%d", start, end);

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"));

//답변글 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

//댓글 갯수 읽어오는 부분 추가

dto.setCommentCount(rs.getInt("commentCount"));


//회원 전용 글쓰기 처리 부분 추가

dto.setId(rs.getString("id"));


arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM consultation");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

//-------------------------------------------


public int adminReply(ConsultationDTO dto)

throws SQLException {

int result = 0;


//답변글 쓰기

String sql = String.format("INSERT INTO consultReply (rid, name, title, content, wdate) VALUES (consultReplySeq.nextval, '%s', '%s','%s', SYSDATE)", dto.getName(), dto.getTitle(), dto.getContent());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 답변글 연결 지정

String sql2 = String.format("UPDATE consultation SET rid=consultReplySeq.currval WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//답변글 읽어오는 전용 메소드 추가

public ConsultationDTO searchByRid(String rid) 

throws SQLException {

ConsultationDTO dto = new ConsultationDTO();


String sql = String.format("SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultReply WHERE rid=%s", rid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto.setRid(rs.getString("rid"));

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 int commentAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

//댓글 쓰기

String sql = String.format("INSERT INTO consultComment (cid, id, name, title, wdate, sid) VALUES (consultCommentSeq.nextval, '%s', '%s', '%s', SYSDATE, %s)", dto.getId(), dto.getName(), dto.getTitle(), dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 댓글 갯수 증가

String sql2 = String.format("UPDATE consultation SET commentCount = commentCount + 1 WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//--------------------------------

//댓글 목록 읽어오는 전용 메소드 추가

public ArrayList<ConsultationDTO> commentLists(String sid) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT cid, id, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate FROM consultComment WHERE sid=%s ORDER BY cid ASC", sid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

ConsultationDTO dto = new ConsultationDTO();

dto.setCid(rs.getString("cid"));

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setTitle(rs.getString("title"));

dto.setWdate(rs.getString("wdate"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

//---------------------------------

//---------------------------------------

//상담 게시판 글 입력 (회원 글쓰기)

public int memberAdd(ConsultationDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("INSERT INTO consultation (sid, name, pw, title, content, wdate, id) VALUES (consultationSeq.nextVal,'%s',encrypt('%s', '%s'),'%s','%s',SYSDATE, '%s')", dto.getName(), dto.getPw(), dto.getName(), dto.getTitle(), dto.getContent(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

//---------------------------------------

//--------------------------------

//회원 전용 삭제 메소드 추가

public int memberRemove(ConsultationDTO dto)

throws SQLException {

int result = 0;

String sql = String.format("DELETE FROM consultation WHERE sid=%s AND id='%s'", dto.getSid(), dto.getId());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

return result;

}

//--------------------------------

}





//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}



function consultSearchSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultSearchForm");


var svalue = document.getElementById("svalue");

var searchMsg = document.getElementById("searchMsg");

searchMsg.style.display = "none";

if (svalue.value == "") {

searchMsg.style.display = "inline";

return;

}

obj.submit();

}


function loginFormSubmit() {

var obj = document.getElementById("loginForm");


var id = document.getElementById("id");

var pw = document.getElementById("pw");

var idMsg = document.getElementById("idMsg");

idMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (id.value == "" || id.value.length > 20) {

idMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}



//댓글 펼치기, 감추기 호출 함수 추가

function commentDivPanel() {

var commentMsg = document.getElementById("commentMsg");

var commentDiv = document.getElementById("commentDiv");

if (commentMsg.innerHTML == "[댓글 펼치기]") {

commentMsg.innerHTML = "[댓글 감추기]";

commentDiv.style.display = "block";

} else {

commentMsg.innerHTML = "[댓글 펼치기]";

commentDiv.style.display = "none";

}

}


function commentInsertSubmit() {

var commentInsertForm = document.getElementById("commentInsertForm");

//데이터 검사 과정 추가

var title = document.getElementById("title");

var commentErrMsg = document.getElementById("commentErrMsg");

commentErrMsg.style.display="none";

if(title.value=="" || title.value.length>200){

commentErrMsg.style.display="inline";

return;

}

commentInsertForm.submit();

}


function consultMemberInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}



//---------------------------------

//회원 전용 삭제 함수 추가

function consultMemberDelete(sid) {

if (confirm("현재 자료를 삭제하시겠습니까?")) {

window.location.href="consultMemberDelete.con?sid="+sid;

}

}

//---------------------------------




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con



-------------------------------------------------------







WRITTEN BY
빨강꼬마

,

---------------------------------------------------------

상담 게시판  답변글 처리

- 답변글 목록 출력 및 내용 보기 페이지 작성


//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


//-----------------------------

//답변글 읽어오는 전용 변수 추가

private String rid;

public String getRid() {

return rid;

}


public void setRid(String rid) {

this.rid = rid;

}

//-----------------------------


public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


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 String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}





//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, rid 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"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

}

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;

}



//상담 게시판 글검색 출력

public ArrayList<ConsultationDTO> searchLists(String skey, String svalue) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, rid FROM consultation WHERE LOWER(%s) LIKE '%%'||LOWER('%s')||'%%' ORDER BY sid DESC", skey, svalue);

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"));

//답변글 번호 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}


//-------------------------------------------

//페이지 처리 후 

//상담 게시판 글목록 출력 (페이지 처리 후, 답변글 처리 후)

public ArrayList<ConsultationDTO> lists(int start, int end) 

throws SQLException {

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

String sql = String.format("SELECT * FROM pageListView WHERE rnum>=%d AND rnum<=%d", start, end);

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"));

//답변글 읽어오는 부분 추가

dto.setRid(rs.getString("rid"));

arrayList.add(dto);

}

rs.close();

return arrayList;

}

public int count()

throws SQLException {

int result = 0;

String sql = String.format("SELECT COUNT(*) AS count FROM consultation");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

result = rs.getInt("count");

}

rs.close();

return result;

}

//-------------------------------------------


public int adminReply(ConsultationDTO dto)

throws SQLException {

int result = 0;


//답변글 쓰기

String sql = String.format("INSERT INTO consultReply (rid, name, title, content, wdate) VALUES (consultReplySeq.nextval, '%s', '%s','%s', SYSDATE)", dto.getName(), dto.getTitle(), dto.getContent());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);

//부모글에 답변글 연결 지정

String sql2 = String.format("UPDATE consultation SET rid=consultReplySeq.currval WHERE sid=%s", dto.getSid());

Statement stmt2 = conn.createStatement();

result = stmt2.executeUpdate(sql2);

return result;

}

//-------------------------------

//답변글 읽어오는 전용 메소드 추가

public ConsultationDTO searchByRid(String rid) 

throws SQLException {

ConsultationDTO dto = new ConsultationDTO();


String sql = String.format("SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate, content FROM consultReply WHERE rid=%s", rid);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto.setRid(rs.getString("rid"));

dto.setName(rs.getString("name"));

dto.setTitle(rs.getString("title"));

dto.setContent(rs.getString("content"));

dto.setWdate(rs.getString("wdate"));

}

rs.close();

return dto;

}

//-------------------------------

}





//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);

}

if (uri.indexOf("consultSearch.con") != -1) {

consultSearch(req, resp);

}

if (uri.indexOf("adminReplyForm.con") != -1) {

adminReplyForm(req, resp);

}

if (uri.indexOf("adminReply.con") != -1) {

adminReply(req, resp);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

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);

}

}

}


private void consultSearch(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//한글 인코딩 처리

//데이터 수신(skey, svalue)

//검색 실행 -> searchLists(skey, svalue)

//검색 결과(ArrayList<ConsultationDTO>)를 

//출력 페이지(consultList.jsp)로 전달

req.setCharacterEncoding("euc-kr");

String skey = req.getParameter("skey");

String svalue = req.getParameter("svalue");


ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

arrayList = dao.searchLists(skey, svalue);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글검색");

RequestDispatcher dispatcher

= req.getRequestDispatcher("consultList.jsp");

dispatcher.forward(req, resp);

}


private void adminReplyForm(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//글번호 수신

//데이터베이스 연결

//글번호에 해당하는 글 정보 읽어온다.

//글 정보(ConsultationDTO)를 출력 페이지로 전달

//답변 글쓰기 페이지(adminReplyForm.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("adminReplyForm.jsp");

dispatcher.forward(req, resp);

}


private void adminReply(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//INSERT, UPDATE 쿼리 메소드 호출

//consultList.con 으로 페이지 이동

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String name = req.getParameter("name");

String title = req.getParameter("title");

String content = req.getParameter("content");

//-----------------------------

//입력 오류 처리 필요

//오라클에서는 입력 데이터에 

//작은따옴표(')가 있으면

//입력 오류 발생됨

//작은따옴표(')를 두 번 입력('')하면 해결됨.

name = name.replaceAll("'", "''");

title = title.replaceAll("'", "''");

content = content.replaceAll("'", "''");

//-----------------------------

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setName(name);

dto.setTitle(title);

dto.setContent(content);

dao.adminReply(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);

}

}





//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

//검색 기준, 검색 단어 수신

String skey = request.getParameter("skey");

if (skey == null) {

skey = "";

}

String svalue = request.getParameter("svalue");

if (svalue == null) {

svalue = "";

}

//제목 글자 수신

String title = (String)request.getAttribute("title");

//페이징 처리 수신

String pageUrl = (String)request.getAttribute("pageUrl");;

if (pageUrl == null) {

pageUrl = "<br>";

}


@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\"><a href=\"consultView.con?sid=%s\">%s</a>", dto.getSid(), dto.getTitle()));

if (dto.getRid() != null) {

str.append("<span style=\"color:blue; font-size:10pt;\">[답변있음]</span>");

}

str.append("</td>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}

StringBuilder options = new StringBuilder();

if (skey.equals("title")) {

options.append("<option value=\"title\" selected=\"selected\">제목</option>");

} else {

options.append("<option value=\"title\">제목</option>");

}

if (skey.equals("content")) {

options.append("<option value=\"content\" selected=\"selected\">내용</option>");

} else {

options.append("<option value=\"content\">내용</option>");

}

if (skey.equals("name")) {

options.append("<option value=\"name\" selected=\"selected\">글작성자</option>");

} else {

options.append("<option value=\"name\">글작성자</option>");

}


%>    

<!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>


</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>[상담게시판_<%=title%>]</h3>

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle"><a href="consultView.con?sid=1">상담 게시판이 오픈되었습니다.</a></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<!-- <td class="bDot">[1][2][3][4]...</td> -->

<td class="bDot"><%=pageUrl%></td>

</tr>

</table>

<form action="consultSearch.con" method="post" id="consultSearchForm">

<table class="style01">

<tr>

<td>

<select id="skey" name="skey"><%=options%></select>

<input type="text" id="svalue" name="svalue" value="<%=svalue%>">

<a href="javascript:consultSearchSubmit()">[검색]</a>

<span id="searchMsg" style="color:red; display:none;">검색 단어를 입력해야 합니다.</span>

</td>

<td style="text-align:right;">

<a href="consultInsertForm.con">[새글쓰기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>




//consultView.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ 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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


//-----------------------------------

//답변글 출력 준비 추가

ConsultationDTO rdto 

= (ConsultationDTO)request.getAttribute("rdto");

String rname = "";

String rtitle = "";

String rwdate = "";

String rcontent = "";

if (rdto != null) {

rname = rdto.getName();

rtitle = rdto.getTitle();

rwdate = rdto.getWdate();

rcontent = rdto.getContent();

rname = rname.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rtitle = rtitle.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("  ", "&nbsp;");

rcontent = rcontent.replaceAll("\n", "<br>");

rcontent = rcontent.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

}


//----------------------------------


%>    

<!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%>

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><%=rtitle%></h3>

<span><%=rname%></span>

<span><%=rwdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<%=rcontent%>

</td>

</tr>

</table>

</div>

</c:if>

</td>

</tr>

</table>

<div style="margin-top:10px;">

<a href="adminReplyForm.con?sid=<%=sid%>">[*답변글쓰기]</a>

<a href="consultList.con">[목록보기]</a>

<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con



----------------------------------------------------

관리자 로그인, 로그아웃

-> 서블릿 주소를 *.mem 으로 처리함.


//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>ConsultationServlet_20121207</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>consultationServlet</servlet-name>

<servlet-class>com.test.ConsultationServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>consultationServlet</servlet-name>

<url-pattern>*.con</url-pattern>

</servlet-mapping>

 

<servlet>

<servlet-name>memberServlet</servlet-name>

<servlet-class>com.test.MemberServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>memberServlet</servlet-name>

<url-pattern>*.mem</url-pattern>

</servlet-mapping>


</web-app>





//MemberDTO.java

package com.test;


public class MemberDTO {

private String id, pw, name, email, tel, wdate;

private int grade;


public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getPw() {

return pw;

}

public void setPw(String pw) {

this.pw = pw;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}

public String getWdate() {

return wdate;

}

public void setWdate(String wdate) {

this.wdate = wdate;

}

public int getGrade() {

return grade;

}

public void setGrade(int grade) {

this.grade = grade;

}

}





//MemberDAO.java

package com.test;


import java.sql.*;


public class MemberDAO {

private Connection conn;

public void connect()

throws ClassNotFoundException, SQLException {

conn = DBConn.getConnection();

}

public void close()

throws SQLException {

DBConn.close();

}


public MemberDTO login(String id, String pw) 

throws SQLException {


MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s' AND pw=encrypt('%s', '%s')", id, pw, id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

public MemberDTO searchId(String id)

throws SQLException {

MemberDTO dto = null;

String sql = String.format("SELECT id, name, email, tel, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate, grade FROM jmember WHERE id='%s'", id);

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {

dto = new MemberDTO();

dto.setId(rs.getString("id"));

dto.setName(rs.getString("name"));

dto.setEmail(rs.getString("email"));

dto.setTel(rs.getString("tel"));

dto.setWdate(rs.getString("wdate"));

dto.setGrade(rs.getInt("grade"));

}

rs.close();

return dto;

}

}






//MemberServlet.java

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;


public class MemberServlet 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("login.mem") != -1) {

login(req,resp);

}

if (uri.indexOf("logout.mem") != -1) {

logout(req,resp);

}

if (uri.indexOf("memberInfo.mem") != -1) {

memberInfo(req,resp);

}

}


private void login(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


//세션 객체 생성 과정

//HttpSession session = req.getSession();

//로그인 성공한 후 세션 객체는

//회원의 아이디 저장용 -> id

//회원의 이름 저장용 -> name

//회원의 회원등급 저장용 -> grade

//세션을 준비한다.

//session.setAttribute("id", dto.getId());


String id = req.getParameter("id");

String pw = req.getParameter("pw");

if (id == null && pw == null) {

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

} else {

//패스워드 검사 과정

MemberDAO dao = new MemberDAO();

MemberDTO dto = null;

try {

dao.connect();

dto = dao.login(id, pw);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

if (dto != null) {

HttpSession session = req.getSession();

session.setAttribute("id", dto.getId());

session.setAttribute("name", dto.getName());

session.setAttribute("grade", dto.getGrade());

req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

} else {

req.setAttribute("error", "true");

RequestDispatcher dispatcher

= req.getRequestDispatcher("login.jsp");

dispatcher.forward(req, resp);

}

}

}


private void logout(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

HttpSession session = req.getSession();

session.invalidate();

resp.sendRedirect("login.mem");

}


private void memberInfo(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//로그인한 회원의 정보 출력 (회원 아이디 필요)

HttpSession session = req.getSession();

String id = (String)session.getAttribute("id");

MemberDTO dto = new MemberDTO();

MemberDAO dao = new MemberDAO();

try {

dao.connect();

dto = dao.searchId(id);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}


req.setAttribute("dto", dto);

RequestDispatcher dispatcher

= req.getRequestDispatcher("memberInfo.jsp");

dispatcher.forward(req, resp);

}


}





//memberInfo.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ page import="com.test.*" %>    

<%

MemberDTO dto

= (MemberDTO)request.getAttribute("dto");

String id = dto.getId();

String name = dto.getName();

String email = dto.getEmail();

String tel = dto.getTel();

String[] array = {"관리자", "직원", "학생", "회원가입"};

String grade = array[dto.getGrade()-1];

%>        

<!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() {

}

</script>


</head>

<body onload="msg()">

<div>

<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>

<div>

<h3>[회원정보]</h3>

<table cellpadding="5" class="style01 borderTop borderBottom">

<tr>

<td width="150">아이디</td><td class="bTitle"><%=id%></td>

</tr>

<tr>

<td width="150">이름</td><td class="bTitle"><%=name%></td>

</tr>

<tr>

<td width="150">이메일</td><td class="bTitle"><%=email%></td>

</tr>

<tr>

<td width="150">전화번호</td><td class="bTitle"><%=tel%></td>

</tr>

<tr>

<td width="150">등급</td><td class="bTitle"><%=grade%></td>

</tr>

</table>

</div>

<div>

<br>

<a href="">[패스워드변경]</a>

<a href="">[회원정보수정]</a>

<a href="">[회원탈퇴]</a>

</div>

</div>


</body>

</html>





//mainMenu.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<div>

<h1>Java 전문 교육센터</h1>

<a href="javascript:">[교육원소개]</a>

<a href="javascript:">[교육과정안내]</a>

<a href="javascript:">[취업지원센터]</a>

<a href="consultList.con">[상담게시판]</a>

<c:choose>

<c:when test="${empty sessionScope.id}">

<a href="member.mem">[회원가입]</a>

<a href="login.mem">[로그인]</a>

</c:when>

<c:otherwise>

<a href="memberInfo.mem">[회원정보]</a>

<a href="logout.mem">[로그아웃]</a>

</c:otherwise>

</c:choose>

<hr>

</div>



//consultView.jsp -> 관리자 전용 메뉴 출력 부분 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    

<%@ 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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


//-----------------------------------

//답변글 출력 준비 추가

ConsultationDTO rdto 

= (ConsultationDTO)request.getAttribute("rdto");

String rname = "";

String rtitle = "";

String rwdate = "";

String rcontent = "";

if (rdto != null) {

rname = rdto.getName();

rtitle = rdto.getTitle();

rwdate = rdto.getWdate();

rcontent = rdto.getContent();

rname = rname.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rtitle = rtitle.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

rcontent = rcontent.replaceAll("  ", "&nbsp;");

rcontent = rcontent.replaceAll("\n", "<br>");

rcontent = rcontent.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

}


//----------------------------------


%>    

<!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>


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


<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%>

<!-- 답변글 내용 출력하는 부분 추가 -->

<c:if test="${!empty rdto}">

<div style="margin-left:50px;margin-top:20px;">

<table cellpadding="5" class="style01 borderTop">

<tr>

<td class="bTitle">

<h3><%=rtitle%></h3>

<span><%=rname%></span>

<span><%=rwdate%></span>

</td>

</tr>

<tr>

<td class="bTitle" style="padding-top:20px;padding-bottom:20px;">

<%=rcontent%>

</td>

</tr>

</table>

</div>

</c:if>

</td>

</tr>

</table>

<div style="margin-top:10px;">

<%-- 관리자 전용 메뉴 출력 부분 --%>

<c:if test="${sessionScope.grade == '1'}">

<a href="adminReplyForm.con?sid=<%=sid%>">[*답변글쓰기]</a>

</c:if>

<a href="consultList.con">[목록보기]</a>

<a href="consultModifyForm.con?sid=<%=sid%>">[글 수정]</a>

<a href="consultRemoveForm.con?sid=<%=sid%>">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>




//모든 JSP 페이지의 메뉴 부분을 아래와 같이 수정 (JSTL 표기 추가)


<%-- 메인메뉴를 import 구문으로 대체 --%>

<c:import url="mainMenu.jsp"></c:import>


'Java > JSP & Servlet' 카테고리의 다른 글

[20121213] 22일차 (상담게시판)  (0) 2012.12.18
[20121212] 21일차 (상담게시판)  (0) 2012.12.18
[20121210] 19일차 (상담게시판)  (0) 2012.12.18
[20121207] 18일차 (상담게시판)  (0) 2012.12.18
[20121206] 17일차  (0) 2012.12.14

WRITTEN BY
빨강꼬마

,

--------------------------------------------------------

상담 게시판 글 삭제 (패스워드 검사 과정 추가)



//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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


%>    

<!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


----------------------------------------------------------

상담게시판 글 검색 (패스워드 검사 과정 추가)







WRITTEN BY
빨강꼬마

,

-------------------------------------

상담 게시판 (JSP, Servlet, JDBC 버전)


1. 웹 상에서 글쓰기, 글보기를 할 수 있는 프로그램.


2. 회원, 비회원 글쓰기 가능. 회원 댓글 쓰기. 회원 가입. 회원 로그인, 로그아웃.


3. 관리자 관리 기능. 관리자 답변글 쓰기.


4. 프로젝트 생성 (ConsultationServlet_20121207)


-------------------------------------

--상담게시판 테이블 (글번호, 글쓴이이름, 패스워드, 제목, 내용, 작성일)


CREATE TABLE consultation (

sid NUMBER  --PK 지정. 시퀀스 지원.

,name NVARCHAR2(20)

,pw VARCHAR2(20) --암호화 지원

,title NVARCHAR2(100)

,content NVARCHAR2(2000)

,wdate DATE --자동 입력. 시스템 현재 날짜.

);


ALTER TABLE consultation

ADD CONSTRAINT consultation_sid_pk PRIMARY KEY(sid);


CREATE SEQUENCE consultationSeq;


INSERT INTO consultation (sid, name, pw, title, content, wdate)

VALUES (consultationSeq.nextVal

,'관리자'

,encrypt('1234', '관리자')  --사용자 정의 암호화 함수

,'상담 게시판이 오픈되었습니다'

,'많은 이용 바랍니다'

,SYSDATE);

COMMIT;


SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

ORDER BY sid DESC;


--SID 기준 검색 쿼리

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

FROM consultation 

WHERE sid=1;


SELECT sid, title, content

FROM consultation 

WHERE sid=1 AND name='관리자' AND pw=encrypt('1234', '관리자');



--이름 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;


--제목 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(title) LIKE '%'||LOWER('html')||'%'

ORDER BY sid DESC;


--내용 기준 검색 (부분 검색 가능하도록 할 것. 대소문자 구분 하지 않도록 할 것)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation 

WHERE LOWER(content) LIKE '%'||LOWER('html')||'%'

ORDER BY sid DESC;




--페이지 처리 쿼리문 (총 게시물 카운트)

SELECT COUNT(*) AS count FROM consultation;



--페이지 처리 쿼리문 (특정 페이지 게시물 읽어오기. 시작번호, 끝번호 필요)

--> 한 페이지당 10개의 게시물 처리

--> 1페이지 게시물은 시작번호 1 ~ 끝번호 10

--> 2페이지 게시물은 시작번호 11 ~ 끝번호 20

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation

ORDER BY sid DESC) data)

WHERE rnum>=1 AND rnum<=10;


CREATE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultation

ORDER BY sid DESC) data);


SELECT * 

FROM pageListView

WHERE rnum>=1 AND rnum<=10;




-----------------------------------------------------------

--관리자 답변글 전용 테이블

CREATE TABLE consultReply (

rid NUMBER  --PK

,name NVARCHAR2(20) --관리자 전용

--,pw VARCHAR2(20)  --관리자 전용이므로 패스워드 저장 안함

,title NVARCHAR2(100)

,content NVARCHAR2(2000)

,wdate DATE

);


ALTER TABLE consultReply

ADD CONSTRAINT consultReply_rid_pk PRIMARY KEY(rid);


CREATE SEQUENCE consultReplySeq;


--답변글과 부모글 연관성 지정 필요

--> 부모글 테이블에 답변글 번호를 저장하는 컬럼 추가 및 FK 지정

ALTER TABLE consultation

ADD rid NUMBER;

ALTER TABLE consultation

ADD CONSTRAINT consultation_rid_fk FOREIGN KEY (rid)

REFERENCES consultReply(rid);


--답변글 추가 쿼리

INSERT INTO consultReply (rid, name, title, content, wdate)

VALUES (consultReplySeq.nextval, '관리자', '예약 확인했습니다.'

,'내일 오전 중으로 연락 드리겠습니다.', SYSDATE);

COMMIT;


--특정 부모글에 답변글 번호를 연결하는 쿼리

UPDATE consultation

SET rid=consultReplySeq.currval

WHERE sid=49;

COMMIT;


--답변글 번호도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid  --답변글 번호 추가

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid  --답변글 번호 추가

FROM consultation 

WHERE sid=1;


--답변글 번호도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid  --답변글 번호 추가

FROM consultation

ORDER BY sid DESC) data);


--답변글 읽어오는 쿼리(RID 필요)

SELECT rid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

FROM consultReply

WHERE rid=1;


----------------------------------------------------

회원 가입, 로그인, 로그아웃 쿼리 작성


--회원 테이블 작성

CREATE TABLE jmember (

id VARCHAR2(20) --PK

,pw VARCHAR2(20) --암호화 지원

,name NVARCHAR2(20)

,email VARCHAR2(100)

,tel VARCHAR2(30)

,wdate DATE

,grade NUMBER DEFAULT 4 --관리자 1, 직원 2, 학생 3, 회원가입 4

);


ALTER TABLE jmember

ADD CONSTRAINT jmember_id_pk PRIMARY KEY(id);


--관리자 전용 입력 쿼리

INSERT INTO jmember (id, pw, name, email, tel, wdate, grade)

VALUES ('admin', encrypt('1234', 'admin'),'관리자', 'admin@test.com', '02-123-1234', SYSDATE, 1);

COMMIT;


--사용자 입력 쿼리 (회원등급이 자동으로 회원가입(4) 등급이 된다)

INSERT INTO jmember (id, pw, name, email, tel, wdate)

VALUES ('test', encrypt('1234', 'test'),'테스트'

, 'test@test.com', '02-111-1111', SYSDATE);

COMMIT;


--회원 확인용 쿼리 (id, pw 동시 검사)

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade

FROM jmember

WHERE id='admin' AND pw=encrypt('1234', 'admin');


--회원 확인용 쿼리 (id만 검사)

SELECT id, name, email, tel

, TO_CHAR(wdate, 'YYYY-MM-DD HH24:MI') AS wdate

, grade

FROM jmember

WHERE id='admin';



--패스워드 수정 쿼리

UPDATE jmember 

SET pw=encrypt('새로운패스워드', '아이디')

WHERE pw=encrypt('기존패스워드', '아이디')

AND id = '아이디';



--회원정보 수정 쿼리

UPDATE jmember

SET name='', email='', tel=''

WHERE pw=encrypt('기존패스워드', '아이디')

AND id = '아이디';



-----------------------------------------------------------

--댓글 저장용 테이블 생성

CREATE TABLE consultComment (

cid NUMBER --PK. 댓글 번호

,id VARCHAR2(20) -- 글쓴이의 아이디

,name NVARCHAR2(20) --글쓴이의 이름

,title NVARCHAR2(200)

,wdate DATE

,sid NUMBER --FK. 부모 글번호

);


ALTER TABLE consultComment

ADD CONSTRAINT consultComment_cid_pk PRIMARY KEY(cid);


ALTER TABLE consultComment

ADD CONSTRAINT consultComment_sid_fk FOREIGN KEY (sid)

REFERENCES consultation(sid);


--댓글 추가 여부를 확인할 수 있는 컬럼을 부모 테이블에 추가

ALTER TABLE consultation

ADD commentCount NUMBER DEFAULT 0;


CREATE SEQUENCE consultCommentSeq;


--댓글 입력 (댓글 테이블에 댓글 내용 추가)

INSERT INTO consultComment (cid, id, name, title, wdate, sid)

VALUES (consultCommentSeq.nextval, 'hong', '홍길동', '댓글 테스트', SYSDATE, 1);

COMMIT;


--댓글 입력 (부모 테이블에 댓글 갯수 증가)

UPDATE consultation

SET commentCount = commentCount + 1

WHERE sid=1;

COMMIT;



--댓글 출력(부모글 기준)

SELECT cid, id, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

FROM consultComment

WHERE sid=1

ORDER BY cid ASC;



--댓글 갯수도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount --댓글 갯수

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid

,commentCount --댓글 갯수

FROM consultation 

WHERE sid=1;



--댓글 갯수도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount --댓글 갯수

FROM consultation

ORDER BY sid DESC) data);



--댓글 삭제 쿼리

DELETE 

FROM consultComment

WHERE cid=1 AND id='hong';




-----------------------------------------------------------

회원 전용 글쓰기 과정 추가


--회원 전용 글쓰기를 위해서 consultation 테이블에 id 컬럼 추가

ALTER TABLE consultation

ADD id VARCHAR2(20);


--글쓰기 내용을 입력하는 과정에서 ID 추가

INSERT INTO consultation (sid, name, pw, title, content, wdate, id)

VALUES (consultationSeq.nextVal

,'관리자'

,encrypt('1234', '관리자')  --사용자 정의 암호화 함수

,'상담 게시판이 오픈되었습니다'

,'많은 이용 바랍니다'

,SYSDATE

, 'hong');

COMMIT;



--아이디도 읽어올 수 있도록 SELECT 쿼리문 변경(검색 쿼리)

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount

,id --아이디

FROM consultation 

WHERE LOWER(name) LIKE '%'||LOWER('홍길동')||'%'

ORDER BY sid DESC;

SELECT sid, name, title, TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

, content

,rid

,commentCount

,id --아이디

FROM consultation 

WHERE sid=1;



--아이디도 읽어올 수 있도록 SELECT 쿼리문 변경(전체 출력 쿼리)

CREATE OR REPLACE VIEW pageListView

AS

SELECT *

FROM (SELECT ROWNUM rnum, data.*

FROM (SELECT sid, name, title

,TO_CHAR(wdate, 'YYYY-MM-DD') AS wdate

,rid

,commentCount

,id --아이디

FROM consultation

ORDER BY sid DESC) data);




------------------------------------------------------------

//web.xml -> 서블릿 주소 등록


//ConsultationServlet.java -> 서블릿 클래스. 서블릿 주소 분석. 액션 처리.


//ConsultationDTO.java


//ConsultationDAO.java


//common.css, table.css -> CSS 전용 파일.


//consultList.jsp -> 글목록 페이지


//consultInsertForm.jsp -> 글 입력 페이지


//consultation.js -> 자바스크립트 전용 파일.


//consultView.jsp -> 글 내용 보기 페이지


//consultPW.jsp -> 패스워드 검사 페이지


//consultModifyForm.jsp -> 글 수정 페이지


//MyUtil.java -> 페이징 처리 전용 메소드 


//adminReplyForm.jsp -> 관리자 답변글 쓰기 전용 페이지


//MemberDTO.java


//MemberDAO.java


//MemberServlet.java -> 회원 관리 전용 서블릿


//login.jsp -> 로그인 화면용 페이지


//memberInfo.jsp -> 회원 정보 출력용 페이지


//mainMenu.jsp -> 주메뉴 전용 페이지


//consultMemberInsertForm.jsp -> 회원 전용 글쓰기 페이지


//memberInsertForm.jsp -> 회원 가입 화면용 페이지


//memberIDCheck.jsp -> Ajax를 이용한 아이디 중복 체크 페이지


//memberInsertOK.jsp -> 회원 가입 완료 메시지 페이지


//memberInsertCancel.jsp -> 회원 가입 실패 메시지 페이지


//memberList.jsp -> 회원 명단 출력 페이지 (관리자, 직원 전용)


//adminUpdateForm.jsp -> 회원 수정 페이지 (관리자 전용)



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


------------------------------------------------------------

상담게시판 글목록 페이지 작성


//web.xml -> 서블릿 주소 등록

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>ConsultationServlet_20121207</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>consultationServlet</servlet-name>

<servlet-class>com.test.ConsultationServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>consultationServlet</servlet-name>

<url-pattern>*.con</url-pattern>

</servlet-mapping>

 

</web-app>




//ConsultationDTO.java

package com.test;


public class ConsultationDTO {

private String sid, name, pw, title, content, wdate;


public String getSid() {

return sid;

}


public void setSid(String sid) {

this.sid = sid;

}


public String getName() {

return name;

}


public void setName(String name) {

this.name = name;

}


public String getPw() {

return pw;

}


public void setPw(String pw) {

this.pw = pw;

}


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 String getWdate() {

return wdate;

}


public void setWdate(String wdate) {

this.wdate = wdate;

}


}




//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;

}


}



//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);

}

}


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);

}


}





//consultList.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\">%s</td>", dto.getTitle()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}


%>    

<!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">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle">상담 게시판이 오픈되었습니다.</td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<td class="bDot">[1][2][3][4]...</td>

</tr>

</table>

<form>

<table class="style01">

<tr>

<td>

<select><option>제목</option></select>

<input type="text">

<a href="">[검색]</a>

</td>

<td style="text-align:right;">

<a href="">[새글쓰기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


------------------------------------------------------------

상담 게시판 비회원 글쓰기 작성 (패스워드 필요)


//consultList.jsp -> 새글쓰기 메뉴에 서블릿 주소 지정

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\">%s</td>", dto.getTitle()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}


%>    

<!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">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle">상담 게시판이 오픈되었습니다.</td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<td class="bDot">[1][2][3][4]...</td>

</tr>

</table>

<form>

<table class="style01">

<tr>

<td>

<select><option>제목</option></select>

<input type="text">

<a href="">[검색]</a>

</td>

<td style="text-align:right;">

<a href="consultInsertForm.con">[새글쓰기]</a>

</td>

</tr>

</table>

</form>

</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);

}

}


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);

}

}




//consultInsertForm.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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>


</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>

<form action="consultInsert.con" method="post" id="consultInsertForm">

<table cellpadding="5" class="style01">

<tr>

<td class="tName" width="100">작성자*</td>

<td class="bTitle"><input type="text" id="name" name="name"><span id="nameMsg" style="color:red; display:none;">1~20자 이름 입력</span></td>

</tr>

<tr>

<td class="tName" width="100">패스워드*</td>

<td class="bTitle"><input type="password" id="pw" name="pw"><span id="pwMsg" style="color:red; display:none;">1~20자 패스워드 입력</span></td>

</tr>

<tr>

<td class="tName" width="100">제목*</td>

<td class="bTitle"><input type="text" style="width:600px;" id="title" name="title"><span id="titleMsg" style="color:red; display:none;">1~100자 제목 입력</span></td>

</tr>

<tr>

<td class="tName" width="100">내용</td>

<td class="bTitle"><textarea style="width:600px;height:200px;" id="content" name="content"></textarea></td>

</tr>

</table>

<table>

<tr>

<td>

<a href="javascript:consultInsertSubmit()">[글쓰기]</a>

<a href="javascript:consultInsertReset()">[새로작성]</a>

<a href="consultList.con">[목록보기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>




//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}




//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;

}



}



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


--------------------------------------------------------

상담 게시판 글 내용 보기



//consultList.jsp -> 제목 부분에 링크 추가

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

@SuppressWarnings("unchecked")

ArrayList<ConsultationDTO> arrayList

= (ArrayList<ConsultationDTO>)request.getAttribute("arrayList");


StringBuilder str = new StringBuilder();

for (ConsultationDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getSid()));

str.append(String.format("<td class=\"bTitle\"><a href=\"consultView.con?sid=%s\">%s</a></td>", dto.getSid(), dto.getTitle()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getName()));

str.append(String.format("<td class=\"bDot\">%s</td>", dto.getWdate()));

str.append("</tr>");

}


%>    

<!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">

<tr>

<td class="tName" width="60">번호</td>

<td class="tName">제목</td>

<td class="tName" width="160">작성자</td>

<td class="tName" width="160">작성일</td>

</tr>

<!-- <tr>

<td class="bDot">1</td>

<td class="bTitle"><a href="consultView.con?sid=1">상담 게시판이 오픈되었습니다.</a></td>

<td class="bDot">관리자</td>

<td class="bDot">2012-03-13</td>

</tr> -->

<%=str%>

</table>

<table class="style01">

<tr>

<td class="bDot">[1][2][3][4]...</td>

</tr>

</table>

<form>

<table class="style01">

<tr>

<td>

<select><option>제목</option></select>

<input type="text">

<a href="">[검색]</a>

</td>

<td style="text-align:right;">

<a href="consultInsertForm.con">[새글쓰기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//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;

}



}




//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);

}

}


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);

}

}



//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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


%>    

<!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="">[글 수정]</a>

<a href="">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>



//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con




--------------------------------------------------------

상담 게시판 글 수정 (패스워드 검사 과정 추가)



//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("<", "&lt;").replaceAll(">", "&gt;");

title = title.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

content = content.replaceAll("<", "&lt;").replaceAll(">", "&gt;");

//공백, 줄바꿈문자, 탭에 대한 특수문자 처리 필요

content = content.replaceAll("  ", "&nbsp;");

content = content.replaceAll("\n", "<br>");

content = content.replaceAll("\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");

//----------------------------------


%>    

<!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="consultModify.con?sid=<%=sid%>">[글 수정]</a>

<a href="">[글 삭제]</a>

</div>

</div>

</div>

</body>

</html>




//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, rid 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"));

//답변글 번호 읽어오는 부분

dto.setRid(rs.getString("rid"));

}

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 modify(ConsultationDTO dto) throws SQLException {

int result =0;


String sql = String.format("UPDATE consultation SET title='%s', CONTENT='%s', wdate=SYSDATE WHERE SID=%s"

, dto.getTitle()

, dto.getContent()

, dto.getSid());

Statement stmt = conn.createStatement();

result = stmt.executeUpdate(sql);


return result;

}


}




//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);

}

}


private void consultList(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

String pageUrl = "[1][2][3][4]...";

//--------------------------------

//페이지 처리 후


//페이지 번호 수신

//한 페이지당 게시물 숫자 지정

//총 게시물 수 확인

//총 페이지수 계산

//예를 들어, 한 페이지당 10개씩 계산

//게시물 21개 있다면

//총 페이지는 3페이지

//특정 페이지의 start, end 값 계산

String pn = req.getParameter("pageNum");

if (pn == null) {

pn = "1";

}

int recordCountPerPage = 10;

int start = (Integer.parseInt(pn) - 1) 

* recordCountPerPage + 1;

int end = Integer.parseInt(pn) * recordCountPerPage;

int recordCount = 0;

//--------------------------------

ArrayList<ConsultationDTO> arrayList

= new ArrayList<ConsultationDTO>();

ConsultationDAO dao = new ConsultationDAO();

try {

dao.connect();

//페이지 처리 전

//arrayList = dao.lists();

//--------------------------

//페이지 처리 후

recordCount = dao.count();

arrayList = dao.lists(start, end);

//--------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

} catch (SQLException e) {

}

}

//---------------------------

//페이지 처리 후

MyUtil myUtil = new MyUtil();

pageUrl = myUtil.pageIndexList(

Integer.parseInt(pn)

, myUtil.getPageCount(recordCountPerPage, recordCount)

, "consultList.con");

//---------------------------

req.setAttribute("arrayList", arrayList);

req.setAttribute("title", "글목록");

req.setAttribute("pageUrl", pageUrl);

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();

ConsultationDTO rdto = null;

try {

dao.connect();

dto = dao.searchBySid(sid);


//----------------------------------

//답변글 읽어오는 부분 추가

if (dto.getRid() != null) {

rdto = dao.searchByRid(dto.getRid());

}

//----------------------------------

}catch(Exception e){

System.out.println(e.toString());

}finally{

try {

dao.close();

}catch(Exception e){

}

}

req.setAttribute("dto", dto);

req.setAttribute("rdto", rdto);

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 {

req.setCharacterEncoding("euc-kr");

String sid = req.getParameter("sid");

String title = req.getParameter("title");

String content = req.getParameter("content");


ConsultationDAO dao = new ConsultationDAO();


try{

dao.connect();


ConsultationDTO dto = new ConsultationDTO();

dto.setSid(sid);

dto.setTitle(title);

dto.setContent(content);


dao.modify(dto);

}catch(Exception e){

System.out.println(e.toString());

}finally{

try{

dao.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


String url = String.format("consultView.con?sid=%s", sid);

resp.sendRedirect(url);

}


}





//consultModifyForm.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 title = dto.getTitle();

String content = dto.getContent();

//------------------------------------

//수정 오류 처리 필요

//수정 폼 화면에서 제목 부분에 큰 따옴표(") 포함시

//제목 일부가 나타나지 않는 문제 발생

//-> 큰따옴표(")를 특수문자(&quot;)로 처리함.

title = title.replaceAll("\"", "&quot;");

//------------------------------------


%>    

<!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>


</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>

<form action="consultModify.con" method="post" id="consultModifyForm">

<%--수정을 위해서 sid 값 재전송 필요 --%>

<input type="hidden" name = "sid" value="<%=sid%>">


<table cellpadding="5" class="style01 borderTop borderBottom">

<!--

<tr>

<td class="tName" width="100">작성자*</td>

<td class="bTitle"><input type="text" id="uname" name="uname" value=""><span id="unameMsg"></span></td>

</tr>

<tr>

<td class="tName" width="100">패스워드*</td>

<td class="bTitle"><input type="password" id="pw" name="pw" value=""><span id="pwMsg"></span></td>

</tr>

-->

<tr>

<td class="tName" width="100">제목*</td>

<td class="bTitle"><input type="text" style="width:600px;" id="title" name="title" value="<%=title%>"><span id="titleMsg"></span></td>

</tr>

<tr>

<td class="tName" width="100">내용</td>

<td class="bTitle"><textarea style="width:600px;height:200px;" id="content" name="content"><%=content%></textarea></td>

</tr>

</table>

<table>

<tr>

<td>

<a href="javascript:consultModifySubmit()">[글수정]</a>

<a href="javascript:consultModifyReset()">[새로작성]</a>

<a href="">[취소]</a>

<a href="consultList.con">[목록보기]</a>

</td>

</tr>

</table>

</form>

</div>

</div>

</body>

</html>





//consultation.js

function consultInsertSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("consultInsertForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var title = document.getElementById("title");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

if (title.value == "" || title.value.length > 100) {

titleMsg.style.display = "inline";

return;

}

obj.submit();

}


function pwFormSubmit() {

//데이터 검사

//에러 메시지 출력

//데이터 전송

var obj = document.getElementById("pwForm");


var name = document.getElementById("name");

var pw = document.getElementById("pw");

var nameMsg = document.getElementById("nameMsg");

nameMsg.style.display = "none";

var pwMsg = document.getElementById("pwMsg");

pwMsg.style.display = "none";

if (name.value == "" || name.value.length > 20) {

nameMsg.style.display = "inline";

return;

}

if (pw.value == "" || pw.value.length > 20) {

pwMsg.style.display = "inline";

return;

}

obj.submit();

}


function consultModifySubmit(){

var obj = document.getElementById("consultModifyForm");

var title = document.getElementById("title");

var titleMsg = document.getElementById("titleMsg");

titleMsg.style.display="none";

if(title.value=="" || title.value.length>100){

titleMsg.style.display="inline";

return;

}

obj.submit();

}




//요청주소

http://localhost:8090/ConsultationServlet_20121207/consultList.con


--------------------------------------------------------






WRITTEN BY
빨강꼬마

,

-----------------------------------------

회원관리+성적처리 프로젝트



Servlet_20121206.war



1. 성적 테이블, 회원 테이블 조인. FK 설정 필요.


2. 회원(회원번호-PK, 이름, 전화번호) -> 이전과 동일


3. 성적 (성적번호-PK, 회원번호-FK, 국어, 영어, 수학) 

-> 이름 대신 회원번호-FK 설정


4. 회원에 회원 등록을 먼저하고, 성적에 성적 입력을 나중에 한다.


----------------------------------------

CREATE TABLE member2 (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member2

ADD CONSTRAINT member2_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE member2Seq;


//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'hong', '111-1111');

INSERT INTO member2 (mid, name, tel) VALUES (member2Seq.nextval, 'park', '222-2222');

COMMIT;



----------------------------------------

CREATE TABLE score2 (

sid NUMBER --PK, 자동 번호 부여

,mid NUMBER --FK

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score2

ADD CONSTRAINT score2_sid_pk PRIMARY KEY (sid);

ALTER TABLE score2

ADD CONSTRAINT score2_kor2_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mat_ck CHECK (mat BETWEEN 0 AND 100);

ALTER TABLE score2

ADD CONSTRAINT score2_mid_fk FOREIGN KEY (mid)

REFERENCES member2(mid);



--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE score2Seq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score2 (sid, mid, kor, eng, mat)

VALUES (score2Seq.nextval, 1, 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+)


--SELECT 쿼리 전용 뷰 생성(scott 계정)

CREATE OR REPLACE VIEW member2Score2View

AS

SELECT m.mid AS mid, sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave    

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR 

mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade  

    FROM member2 m, score2 s

    WHERE m.mid = s.mid(+);


--뷰를 이용한 SELECT 쿼리 실행

SELECT mid, sid, name, kor, eng, mat, tot, ave, grade 

FROM member2Score2View;



-----------------


//DBConn.java


//Member2DTO.java


//Score2DTO.java


//Member2DAO.java


//Score2DAO.java


//Member2Score2Servlet.java


//Member2List.jsp


//Member2InsertForm.jsp


//Score2List.jsp


//Score2InsertForm.jsp


//web.xml


//요청주소

http://localhost:8090/Servlet_20121206/Member2List.ms


-------------------------------------------------------



WRITTEN BY
빨강꼬마

,

---------------------------------------

재전송 방법


1. sendRedirect()

요청 주소 -> A

응답 주소 -> B

브라우저 주소 -> A -> B


2. forward()

요청 주소 -> A (서블릿)

응답 주소 -> B (JSP)

브라우저 주소 -> A -> A


-----------------------------------

forward() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


-특징

. 재전송 (서버 차원에서 URL를 다른 페이지로 변경해버린다)

. 입력(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 출력(HTML이 포함된 JSP 페이지) 전용 페이지

. request.setAttribute() 메소드를 이용해서 데이터를 재전송시킬 수 있다.

. 받을 때는 request.getAttribute() 메소드 이용.

. 재전송 데이터는 객체 형태의 데이터는 모두 가능.

. 서버 차원에서 URL를 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 없다.


-----------------------------------

sendRedirect() 메소드에 의한 데이터 재전송

- 입력, 처리, 출력 페이지를 별도로 작성.


-특징

. 재전송 (서버 차원에서 URL를 다른 페이지로 변경해버린다)

. 요청페이지(HTML이 포함된 JSP 페이지) -> 처리(Servlet) -> 결과페이지(HTML이 포함된 JSP 페이지) 전용 페이지

. 클라이언트 차원에서 URL를 다른 페이지로 변경하기 때문에 클라이언트는 변경된 사실을 알 수 있다.

. 재전송 데이터는 GET 방식으로 전송 가능.

. 재전송 가능한 데이터는 문자열 형태의 데이터만 가능.


--------------------------------------

데이터 송수신 테스트9

-> Send09, Receive09를 모두 서블릿으로 변경

-> HTML 페이지가 있는 인터페이스는 JSP로 작성.

-> 액션은 Servlet이 담당.


//Send09.java -> 서블릿 클래스. 주소 처리 담당. 액션 담당.

package com.test;


import java.io.IOException;


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 Send09 extends HttpServlet {


@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 {

//입력 화면 구성용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Send09.jsp");

dispatcher.forward(req, resp);

}


}




//Send09.jsp -> 데이터 입력용 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

//이름, 전화번호가 비어있는지 검사하는 과정 추가

//이름, 전화번호가 채워진 경우만 데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>데이터 송수신 테스트9</h2>

<!-- <form> 태그에서 action, method 속성 필수 -->

<form action="Receive09" method="post">

<!-- JSP에서는 식별자를 name 속성으로 구분 -->

이름 <input type="text" name="name"><br>

전화 <input type="text" name="tel"><br>

<!-- submit 버튼을 클릭하면 데이터 전송됨 -->

<!-- <input type="submit" value="회원가입"><br> -->

<!-- 자바스크립트 연동시 submit 대신 button 으로 처리 -->

<input type="button" value="회원가입"

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화번호를 채워야 합니다.</span>

</form>

</div>

</body>

</html>




//Receive09.java  -> 서블릿 클래스. 주소 처리 담당. 액션 담당.

package com.test;


import java.io.IOException;


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 Receive09 extends HttpServlet {


@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 {

//액션 처리 코드

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

//결과 메시지 생성

StringBuilder str = new StringBuilder();

str.append(String.format("name:%s, tel:%s", name, tel));

//결과 메시지 재전송

req.setAttribute("str", str);

//결과 출력용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Receive09.jsp");

dispatcher.forward(req, resp);

}


}





//Receive09.jsp -> 결과 출력용 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//결과 메시지 수신

StringBuilder str = (StringBuilder)request.getAttribute("str");

%>

<!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>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트9</h2>

<h3><%=str%></h3>

</div>

</body>

</html>




//web.xml -> 서블릿 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Send09</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Send09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive09</servlet-name>

<servlet-class>com.test.Receive09</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive09</servlet-name>

<url-pattern>/Receive09</url-pattern>

</servlet-mapping>

  

</web-app>




//요청주소

http://localhost:8090/프로젝트이름/서블릿이름

http://localhost:8090/Servlet_20121205/Send09



--------------------------------------

데이터 송수신 테스트10

-> Send10, Receive10을 하나의 서블릿으로 변경

-> 서블릿 주소를 확장자로 통합 처리(*.확장자)

-> 서블릿 주소 분석 과정 필요

-> HTML 페이지가 있는 인터페이스는 JSP로 작성.

-> 액션은 Servlet이 담당.


//SendAndReceive10.java -> 서블릿 클래스. 주소 분석 과정. 액션 담당.

package com.test;


import java.io.IOException;


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 SendAndReceive10 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();

//System.out.println(uri);

if (uri.indexOf("Send10.do") != -1) {

Send10(req, resp);

}

if (uri.indexOf("Receive10.do") != -1) {

Receive10(req, resp);

}

}

private void Send10(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//입력 화면 구성용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Send10.jsp");

dispatcher.forward(req, resp);

}

private void Receive10(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

//결과 메시지 생성

StringBuilder str = new StringBuilder();

str.append(String.format("name:%s, tel:%s", name, tel));

//결과 메시지 재전송

req.setAttribute("str", str);

//결과 출력용 인터페이스 코드 작성

//-> 전용 JSP 페이지로 연결함.

RequestDispatcher dispatcher

= req.getRequestDispatcher("Receive10.jsp");

dispatcher.forward(req, resp);

}

}





//Send10.jsp -> 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

//이름, 전화번호가 비어있는지 검사하는 과정 추가

//이름, 전화번호가 채워진 경우만 데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>데이터 송수신 테스트10</h2>

<!-- <form> 태그에서 action, method 속성 필수 -->

<form action="Receive10.do" method="post">

<!-- JSP에서는 식별자를 name 속성으로 구분 -->

이름 <input type="text" name="name"><br>

전화 <input type="text" name="tel"><br>

<!-- submit 버튼을 클릭하면 데이터 전송됨 -->

<!-- <input type="submit" value="회원가입"><br> -->

<!-- 자바스크립트 연동시 submit 대신 button 으로 처리 -->

<input type="button" value="회원가입"

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화번호를 채워야 합니다.</span>

</form>

</div>

</body>

</html>




//Receive10.jsp -> 인터페이스 담당.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

//결과 메시지 수신

StringBuilder str = (StringBuilder)request.getAttribute("str");

%>

<!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>Insert title here</title>

</head>

<body>

<div>

<h2>데이터 송수신 테스트10</h2>

<h3><%=str%></h3>

</div>

</body>

</html>




//web.xml -> 서블릿 주소 등록. 서블릿 주소를 확장자로 통합 처리.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Send09</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>send09</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Send09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive09</servlet-name>

<servlet-class>com.test.Receive09</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive09</servlet-name>

<url-pattern>/Receive09</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>sendandreceive10</servlet-name>

<!-- 서블릿 주소 분석 과정 필요 -->

<servlet-class>com.test.SendAndReceive10</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sendandreceive10</servlet-name>

<!-- 서블릿 주소를 확장자로 통합 처리

이름에 관계없이 확장자만 do인 경우는

모두 서블릿으로 처리됨 -->

<url-pattern>*.do</url-pattern>

</servlet-mapping>

  

</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Send10.do


------------------------------------

문제) 이름, 국어, 영어, 수학 점수를 입력 받아서 총점, 평균 계산해서 결과 출력하는 페이지 작성. JSP&Servlet 이용.


//SungjukServlet.java ->서블릿 주소 분석 과정 추가.

//-> 이름, 국어, 영어, 수학 점수를 수신해서 총점, 평균 계산

package com.test;


import java.io.IOException;


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 SungjukServlet 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();

//(브라우저에 요청된 주소를 프로그램적으로 읽어옴)

//System.out.println(uri); //(확인용) 

//(uri.indexOf("")특정 문자열이 존재하는지 어떤지 알려주는 기능/ -1이 아니면 존재함.)

if (uri.indexOf("Send11.sung") != -1) {

Send11(req, resp);

}

if (uri.indexOf("Receive11.sung") != -1){

Receive11(req, resp);

}

}

private void Send11(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//입력 화면 구성용 인터페이스 코드 작성(예전)

//-> 전용 JSP 페이지로 연결함.

//forward()

RequestDispatcher dispatcher 

= req.getRequestDispatcher("Send11.jsp");

dispatcher.forward(req, resp);

}

private void Receive11(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//액션 처리 코드

//송수신 데이터에서 한글이 포함된 경우는 인코딩 추가 필수

req.setCharacterEncoding("euc-kr");


String name = req.getParameter("name");

String kors = req.getParameter("kor");

String engs = req.getParameter("eng");

String mats = req.getParameter("mat");

int kor = Integer.parseInt(kors);

int eng = Integer.parseInt(engs);

int mat = Integer.parseInt(mats);

int tot = kor+eng+mat;

double ave= tot/(double)3;

//결과 메시지 재전송

req.setAttribute("name", name);

req.setAttribute("kor", kor);

req.setAttribute("eng", eng);

req.setAttribute("mat", mat);

req.setAttribute("tot", tot);

req.setAttribute("ave", ave);

//결과 출력용 인터페이스 코드 작성(예전)

//-> 전용 JSP 페이지로 연결함.

//forward()

RequestDispatcher dispatcher 

= req.getRequestDispatcher("Receive11.jsp");

dispatcher.forward(req, resp);

}


}





//Send11.jsp

//-> 이름, 국어, 영어, 수학 점수를 입력받는 페이지 작성. 서버에 데이터 전송.

//-> 데이터 검사 과정 추가. 자바스크립트 이용.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

var name = document.getElementById("name");

var korObj = document.getElementById("kor");

var engObj = document.getElementById("eng");

var matObj = document.getElementById("mat");

var kor = korObj.value;

var eng = engObj.value;

var mat = matObj.value;

var msg1 = document.getElementById("msg1");

var msg2 = document.getElementById("msg2");

msg1.style.display = "none";

msg2.style.display = "none";

if(name.value =="" || kor =="" || mat =="" ||eng==""){

msg1.style.display ="inline";

if(name.value ==""){

name.focus();

}

if(kor==""){

korObj.focus();

}

if(mat ==""){

matObj.focus();

}

if(eng ==""){

engObj.focus();

}

} else if(kor.match(/[^0-9]/) ||eng.match(/[^0-9]/) || mat.match(/[^0-9]/)

|| parseInt(kor)>100 || parseInt(eng)>100 || parseInt(mat)>100){

msg2.style.display ="inline";

if(mat.match(/[^0-9]/) || parseInt(mat)>100){

matObj.value = "";

matObj.focus();

}

if(eng.match(/[^0-9]/) || parseInt(eng)>100){

engObj.value = "";

engObj.focus();

}

if(kor.match(/[^0-9]/) || parseInt(kor)>100){

korObj.value = "";

korObj.focus();

}


}else {

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>성적 입력</h2>

<form action = "Receive11.sung" method ="post">

이름<input type="text" name="name" id="name"><br>

국어<input type="text" name="kor" id="kor">(0~100)<br>

영어<input type="text" name="eng" id="eng">(0~100)<br>

수학<input type="text" name="mat" id="mat">(0~100)<br>

<input type = "button" value="입력" 

onclick = "myFunc(this)"><br>

<span id = "msg1" style ="color:red; display:none;">모든 항목을 채우세요.</span> 

<span id = "msg2" style ="color:red; display:none;">점수는 범위에 맞는, 숫자를 쓰세요.</span> 

</form>

</div>

</body>

</html>




//Receive11.jsp

//-> 결과 메시지 출력.

//-> 테이블 태그 이용해서 표 형태로 출력.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String name = (String) request.getAttribute("name");


int kor = (Integer) request.getAttribute("kor");

int eng = (Integer) request.getAttribute("eng");

int mat = (Integer) request.getAttribute("mat");

int tot = (Integer) request.getAttribute("tot");

double ave = (Double) request.getAttribute("ave");


StringBuilder str = new StringBuilder();

str.append(String

.format("<table><tbody><th>이름</th><th>국어</th><th>영어</th><th>수학</th><th>총점</th><th>평균</th>"));

str.append(String

.format("<tr><td>%s</td><td>%d</td><td>%d</td><td>%d</td><td>%d</td><td>%.2f</td></tr></tbody></table>",

name, kor, eng, mat, tot, ave));

%>

<!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>Insert title here</title>

</head>

<body>

<div>

<h2>성적 총점과 평균까지</h2>

<div><%=str%></div>

</div>

</body>

</html>




//web.xml -> 확장자 .sung로 서블릿 주소 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>sungjuk11</servlet-name>

<servlet-class>com.test.SungjukServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>sungjuk11</servlet-name>

<url-pattern>*.sung</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Send11.sung


-----------------------------------------

문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성. 

오라클, JSP, Servlet 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333

----------------------------


//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}





//MemberDTO.java -> 자료 처리 전용 클래스.

package com.test;


public class MemberDTO {

private int mid;

private String name, tel;


public int getMid() {

return mid;

}

public void setMid(int mid) {

this.mid = mid;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getTel() {

return tel;

}

public void setTel(String tel) {

this.tel = tel;

}


}




//MemberServlet.java -> 서블릿. 서블릿 주소 분석. 입력 액션, 출력 액션.

package com.test;


import java.io.IOException;


import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;

import java.util.ArrayList;


public class MemberServlet 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("Member.me") != -1) {

member(req, resp);

}

if (uri.indexOf("MemberInsert.me") != -1) {

memberInsert(req, resp);

}

}


private void member(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터베이스 연결

//자료를 읽어온다.

//자료 재전송

String count = "";

ArrayList<MemberDTO>

arrayList = new ArrayList<MemberDTO>();

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//SELECT 실행 구문 -> 회원수 -> count 변수에 저장

String sql1 = String.format("SELECT COUNT(*) AS count FROM member");

Statement stmt = conn.createStatement();

ResultSet rs1 = stmt.executeQuery(sql1); //결과집합

while(rs1.next()) { //row 단위 접근

int result = rs1.getInt("count"); //column 단위 접근

count = String.format("%d", result);

}

rs1.close();

//SELECT 실행 구문 -> 회원 명단 -> 테이블 태그 이용-> str 변수에 누적

String sql2 = String.format("SELECT mid, name, tel FROM member ORDER BY mid");

ResultSet rs2 = stmt.executeQuery(sql2); //결과집합

while(rs2.next()) { //row 단위 접근

int mid = rs2.getInt("mid"); //column 단위 접근

String name = rs2.getString("name");

String tel = rs2.getString("tel");


MemberDTO dto = new MemberDTO();

dto.setMid(mid);

dto.setName(name);

dto.setTel(tel);

arrayList.add(dto);

}

rs2.close();

req.setAttribute("count", count);

req.setAttribute("arrayList", arrayList);

} catch(Exception e) {

System.out.println(e.toString());

}

//MemberServlet.jsp 페이지로 연결

//forward() 메소드 이용

RequestDispatcher dispatcher 

= req.getRequestDispatcher("MemberServlet.jsp");

dispatcher.forward(req, resp);

}


private void memberInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//자료를 입력한다.

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String tel = req.getParameter("tel");

try {

Connection conn = DBConn.getConnection();

String sql = String.format("INSERT INTO member (mid,name,tel) VALUES (memberSeq.nextval, '%s', '%s')", name, tel);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch(Exception e) {

System.out.println(e.toString());

}

//Member.me 서블릿을 재요청 한다.

//sendRedirect() 메소드 이용

String url = String.format("Member.me");

resp.sendRedirect(url);

}

}





//MemberServlet.jsp -> 입력, 출력 화면 구성용 페이지. 결과 메시지 출력.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>    

<%

String count = (String)request.getAttribute("count");

StringBuilder str = new StringBuilder();

@SuppressWarnings("unchecked")

ArrayList<MemberDTO>

arrayList = (ArrayList<MemberDTO>)request.getAttribute("arrayList");

for (MemberDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td>%d</td>", dto.getMid()));

str.append(String.format("<td>%s</td>", dto.getName()));

str.append(String.format("<td>%s</td>", dto.getTel()));

str.append("</tr>");

}

%>    

<!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>Insert title here</title>


<script type="text/javascript">

function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈 칸 검사

if (name.value == ""

|| tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>이름과 전화번호를 저장하는 프로그램(JSP, Servlet, JDBC)</h2>

<form action="MemberInsert.me" method="post">

이름 <input type="text" name="name" id="name"><br>

전화 <input type="text" name="tel" id="tel"><br>

<input type="button" value=" 등록 "

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 전화를 입력해야 합니다.</span>

</form>

<h3>출력-------------</h3>

<div>

<h4>전체 회원수 : <%=count%> 명</h4>

<table style="width:400px;" border="1">

<tbody>

<tr><th>번호</th><th>이름</th><th>전화</th></tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//web.xml -> 확장자(*.me)에 의한 서블릿 주소 등록.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>member11</servlet-name>

<servlet-class>com.test.MemberServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>member11</servlet-name>

<url-pattern>*.me</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Member.me




------------------------------------------

문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 

오라클, JSP, Servlet 이용. 

총점 기준 정렬(내림차순) 출력.

ScoreDTO, ScoreDAO 작성 추가.



판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 ----------------

이름 [kim   ]

국어 [80    ]

영어 [90    ]

수학 [80    ]

[ 등록 ]


---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------




//DBConn.java

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}






//ScoreDTO.java

package com.test;


public class ScoreDTO {


private String name;

private int kor, eng, mat;


private int tot;

private double ave;

private String grade;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getKor() {

return kor;

}

public void setKor(int kor) {

this.kor = kor;

}

public int getEng() {

return eng;

}

public void setEng(int eng) {

this.eng = eng;

}

public int getMat() {

return mat;

}

public void setMat(int mat) {

this.mat = mat;

}

public int getTot() {

return tot;

}

public void setTot(int tot) {

this.tot = tot;

}

public double getAve() {

return ave;

}

public void setAve(double ave) {

this.ave = ave;

}

public String getGrade() {

return grade;

}

public void setGrade(String grade) {

this.grade = grade;

}

}







//ScoreDAO.java

package com.test;


import java.sql.*;

import java.util.*;


public class ScoreDAO {


private Connection conn;


public void connect()

throws SQLException, ClassNotFoundException{

conn = DBConn.getConnection();


}


public void close() 

throws SQLException{

DBConn.close();

conn = null;

}



public int add(ScoreDTO dto) 

throws SQLException{

int rowCount =0;


String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %d, %d, %d)", dto.getName(), dto.getKor(), dto.getEng(), dto.getMat());

Statement stmt = conn.createStatement();

rowCount = stmt.executeUpdate(sql);


return rowCount;

}


public ArrayList<ScoreDTO> lists() 

throws SQLException{

ArrayList<ScoreDTO> arrayList = new ArrayList<ScoreDTO>();


String sql = String.format("SELECT name, kor, eng, mat, (kor+eng+mat) AS tot, (kor+eng+mat)/3 AS ave, CASE WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락' WHEN ((kor+eng+mat)/3 >= 60) THEN '합격' ELSE '불합격' END AS grade FROM score ORDER BY tot DESC");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql);


while(rs.next()){

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");


ScoreDTO dto = new ScoreDTO();

dto.setName(name);

dto.setKor(kor);

dto.setEng(eng);

dto.setMat(mat);

dto.setTot(tot);

dto.setAve(ave);

dto.setGrade(grade);


arrayList.add(dto);

}


rs.close();


return arrayList;


}

}






//ScoreServlet.java

package com.test;


import java.io.IOException;

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 ScoreServlet 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("Score.sc") != -1) {

score(req, resp);

}

if (uri.indexOf("ScoreInsert.sc") != -1) {

scoreInsert(req, resp);

}

}

private void score(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터베이스 연결

//자료를 읽어온다.

//자료 재전송

ScoreDAO dao = new ScoreDAO();

ArrayList<ScoreDTO>

arrayList = new ArrayList<ScoreDTO>();

try {

dao.connect();

arrayList = dao.lists();

} catch(Exception e) {

System.out.println(e.toString());

}

req.setAttribute("arrayList", arrayList);


//ScoreServlet.jsp 페이지로 연결

//forward() 메소드 이용

RequestDispatcher dispatcher 

= req.getRequestDispatcher("ScoreServlet.jsp");

dispatcher.forward(req, resp);

}


private void scoreInsert(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//데이터 수신

//데이터베이스 연결

//자료를 입력한다.

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String kor = req.getParameter("kor");

String eng = req.getParameter("eng");

String mat = req.getParameter("mat");

ScoreDAO dao = new ScoreDAO();

try {

dao.connect();

ScoreDTO dto = new ScoreDTO();

dto.setName(name);

dto.setKor(Integer.parseInt(kor));

dto.setEng(Integer.parseInt(eng));

dto.setMat(Integer.parseInt(mat));

dao.add(dto);

} catch(Exception e) {

System.out.println(e.toString());

}

//Score.sc 서블릿을 재요청 한다.

//sendRedirect() 메소드 이용

String url = String.format("Score.sc");

resp.sendRedirect(url);

}

}





//ScoreServlet.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%@ page import="java.util.*" %>    

<%@ page import="com.test.*" %>       

<%

StringBuilder str = new StringBuilder();

@SuppressWarnings("unchecked")

ArrayList<ScoreDTO>

arrayList = (ArrayList<ScoreDTO>)request.getAttribute("arrayList");


int rank = 0;

for (ScoreDTO dto : arrayList) {

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td><td class=\"style1\">%s</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%.1f</td><td class=\"style1\">%s</td>"

, ++rank

, dto.getName()

, dto.getKor()

, dto.getEng()

, dto.getMat()

, dto.getTot()

, dto.getAve()

, dto.getGrade()));

str.append("</tr>");

}


%>    

<!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>Insert title here</title>


<style type="text/css">

.subject {

width:80px;

}

.style1 {

text-align: center;

}

.style2 {

text-align: right;

}

</style>


<script type="text/javascript">

function myFunc(obj){

var name = document.getElementById('name');

var kor = document.getElementById('kor');

var eng = document.getElementById("eng");

var mat = document.getElementById("mat");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if(name.value == "" || kor.value == "" || eng.value ==""|| 


mat.value==""){

msg.style.display = "inline";

return;

//숫자 검사

if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)


||mat.value.match(/[^0-9]/)){

msg.style.display = "inline";

return;

//범위 검사

if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 


||parseInt(mat.value)>100 ){

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}

</script>


</head>

<body>

<div>

<h2>성적 처리(JSP, Servlet, JDBC)</h2>

<form action="ScoreInsert.sc" method="post">

이름 <input type="text" name="name" id="name"><br> 

국어 <input type="text" name="kor" id="kor" 


class="subject"><br>

영어 <input type="text" name="eng" id="eng" 


class="subject"><br>

수학 <input type="text" name="mat" id="mat" 


class="subject"><br>

<input type="button" value=" 등록 "

onclick="myFunc(this)"><br>

<span id="msg" style="color:red; display:none;">이름, 국어, 


영어, 수학을 입력해야 합니다.<br>국어, 영어, 수학을 0~100 사이의 숫자를 입력


해야 합니다.</span>

</form>

<h3>출력 ------------</h3>

<div>

<table border="1" style="width:500px;">

<tbody>

<tr>

<th>등수</th>

<th>이름</th>

<th>국어</th>

<th>영어</th>

<th>수학</th>

<th>총점</th>

<th>평균</th>

<th>판정</th>

</tr>

<%=str%>

</tbody>

</table>

</div>

</div>

</body>

</html>




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121205</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

<servlet>

<servlet-name>score11</servlet-name>

<servlet-class>com.test.ScoreServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>score11</servlet-name>

<url-pattern>*.sc</url-pattern>

</servlet-mapping>


</web-app>




//요청주소

http://localhost:8090/Servlet_20121205/Score.sc


--------------------------------------


'Java > JSP & Servlet' 카테고리의 다른 글

[20121207] 18일차 (상담게시판)  (0) 2012.12.18
[20121206] 17일차  (0) 2012.12.14
[20121204] 15일차 (Servlet JDBC 연동)  (0) 2012.12.04
[20121203] 14일차 (Servlet)  (0) 2012.12.04
[20121122] 8일차 (직원관리 최종버젼)  (0) 2012.12.04

WRITTEN BY
빨강꼬마

,

Servlet & JDBC



1. 다이나믹 웹 프로젝트 생성 후에 WebContent > WEB-INF > lib 폴더에 ojdbc14.jar 파일을 넣어야 함.


------------------------------------------------------------------------------------

DBConn 클래스를 이용한 오라클 연결 테스트


//DBConn.java -> Java Resources > src 폴더에 패키지 생성 후 복사할 것.

package com.test;


import java.sql.*;


public class DBConn {

//Singleton pattern

private static Connection dbConn;

public static Connection getConnection()

throws SQLException, ClassNotFoundException {

if (dbConn == null) {


String url = "jdbc:oracle:thin:@localhost:1521:xe";

String user = "scott";

String pw = "tiger";

Class.forName("oracle.jdbc.driver.OracleDriver");

dbConn = DriverManager.getConnection(url, user, pw);


}

return dbConn;

}

public static void close()

throws SQLException {

if (dbConn != null) {

if (!dbConn.isClosed()) {

dbConn.close();

}

}

dbConn = null;

}

}




//Oracle01.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle01 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 {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String str = "연결 실패!";

Connection conn = null;

try {

conn = DBConn.getConnection();

str = "연결 성공!";

}catch(Exception e){

System.out.println(e.toString());

}finally {

try {

DBConn.close();

}catch(Exception e){

System.out.println(e.toString());

}

}


out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>오라클 연결 테스트</h2>");

out.print("<div>");

out.print(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


}



------------------------------------------------------------------------------------

SQL 쿼리 전송 테스트1 (scott 계정)


//회원 테이블 생성. 회원번호, 이름, 전화번호. 시퀀스 객체 생성.

CREATE TABLE member (

mid NUMBER --PK

,name VARCHAR2(10)

,tel VARCHAR2(20)

);


ALTER TABLE member

ADD CONSTRAINT member_mid_pk PRIMARY KEY(mid);


CREATE SEQUENCE memberSeq;



//회원 테이블에 자료 입력. INSERT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//INSERT INTO member (mid, name, tel) VALUES (memberSeq.nextval, 'hong', '111-1111')



//DBConn.java


//Oracle02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Oracle02 extends HttpServlet {


@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 {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

//html 도큐먼트를 동적 생성하기 위한 부분

PrintWriter out = resp.getWriter();

String str = "";

try {

//연결

Connection conn = DBConn.getConnection();

//쿼리 준비

//쿼리 작성시 끝에 ; 표시하지 말것.

String sql = String.format("INSERT INTO member (mid,name, tel) VALUES (memberSeq.nextval, 'lee', '123-1234')");

//쿼리 실행

//Java에서 쿼리를 실행하면 

//내부적으로 COMMIT은 자동 실행됨.

//executeUpdate() 메소드는 DML문인 경우만 실행.

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(sql);

//결과 메시지

str = String.format("%d개의 행이 입력되었습니다. <br>"

, count);

}catch(Exception e) {

System.out.println(e.toString());

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>SQL 쿼리 전송 테스트1</h2>");

out.print("<div>");

out.print(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}





//web.xml




-----------------------------------------------------------------------------------

회원 테이블 자료 출력 테스트. SELECT 쿼리.

//쿼리문의 끝에 ; 표시하지 말것.

//SELECT mid, name, tel FROM member ORDER BY mid


//DBConn.java


//Oracle03.java


//web.xml



------------------------------------------------------------------------------------

문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성2. 오라클, JSP 이용.

데이터 입력과 출력을 동시 실행. 


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


----------------------------

전체 회원수 : 2명

----------------------------

회원번호 이름   전화번호

----------------------------

1        홍길동 010-123-1234

2        김길동 010-222-3333






------------------------------------------

문제) 여러명의 국어, 영어, 수학 점수를 입력 받아서 

총점, 평균, 판정 결과 출력하는 JDBC 프로그램 작성. 오라클, Servlet 이용. 

총점 기준 정렬(내림차순) 출력.


판정 기준은

합격 -> 과목별로 40점 이상이면서, 평균이 60점 이상

과락 -> 과목중에 40점 미만이 있고, 평균은 60점 이상

불합격 -> 평균이 60점 미만


평균이 60점 이상 -> 합격

평균이 60점 미만 -> 불합격


합격 또는 과락 구분은 -> 국어, 영어, 수학 점수가 모두 40점 이상인 확인.


실행 예)

성적 입력 ----------------

이름 [kim   ]

국어 [80    ]

영어 [90    ]

수학 [80    ]

[ 등록 ]


---------------------------------------

    이름 국어 영어 수학 총점 평균 판정

---------------------------------------

1등 hong 100  100  100  300  100.0 합격

2등 kim   80   90   80  ..    ..   합격

---------------------------------------


---------------------------------------------

--오라클에 성적 저장용 테이블 생성

CREATE TABLE score (

sid NUMBER --PK, 자동 번호 부여

,name VARCHAR2(10)

,kor NUMBER(3) --CK (0~100)

,eng NUMBER(3) --CK (0~100)

,mat NUMBER(3) --CK (0~100)

);


--제약 조건 추가

ALTER TABLE score

ADD CONSTRAINT score_sid_pk PRIMARY KEY (sid);

ALTER TABLE score

ADD CONSTRAINT score_kor_ck CHECK (kor BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_eng_ck CHECK (eng BETWEEN 0 AND 100);

ALTER TABLE score

ADD CONSTRAINT score_mat_ck CHECK (mat BETWEEN 0 AND 100);


--자동 번호 부여 시퀀스 객체 생성

CREATE SEQUENCE scoreSeq;



--INSERT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

INSERT INTO score (sid, name, kor, eng, mat)

VALUES (scoreSeq.nextval, 'hong', 100, 100, 100)


--SELECT 쿼리 샘플 (쿼리 끝 부분에 ; 표시하지 말 것)

SELECT sid, name, kor, eng, mat

, (kor+eng+mat) AS tot

, (kor+eng+mat)/3 AS ave


--, 조건검사 쿼리 추가 ->합격, 불합격, 과락 출력

, CASE

WHEN ((kor+eng+mat)/3 >= 60) AND (kor<40 OR eng<40 OR mat<40) THEN '과락'

WHEN ((kor+eng+mat)/3 >= 60) THEN '합격'

ELSE '불합격'

END AS grade


FROM score

ORDER BY tot DESC


--scoreView를 이용한 SELECT 쿼리

SELECT sid, name, kor, eng, mat, tot, ave, grade 

FROM scoreView 

ORDER BY tot DESC



//DBConn.java


//Oracle08.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle08 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 {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

StringBuilder str = new StringBuilder();

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//SELECT 실행 구문 -> 회원 명단 -> 테이블 태그 이용-> STR 변수에 누적

String sql = String.format("SELECT sid, name, kor, eng, mat, tot, ave, grade FROM scoreView ORDER BY tot DESC");


Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery(sql); //결과집합

int rank = 0;

while(rs.next()) { //row 단위 접근

String name = rs.getString("name");

int kor = rs.getInt("kor");

int eng = rs.getInt("eng");

int mat = rs.getInt("mat");

int tot = rs.getInt("tot");

double ave = rs.getDouble("ave");

String grade = rs.getString("grade");

str.append("<tr>");

str.append(String.format("<td class=\"style1\">%d</td><td class=\"style1\">%s</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%d</td><td class=\"style2\">%.1f</td><td class=\"style1\">%s</td>"

, ++rank, name, kor, eng, mat, tot, ave, grade));

str.append("</tr>");

}

rs.close();

} catch(Exception e) {

System.out.println(e.toString());

}

//HTML 도큐먼트를 동적 생성하기 위한 부분

PrintWriter out = resp.getWriter();


out.println(" <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println(" <html>");

out.println(" <head>");

out.println(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println(" <title>Insert title here</title>");

out.println(" ");

out.println(" <style type=\"text/css\">");

out.println(" .subject {");

out.println(" width:80px;");

out.println(" }");

out.println(" .style1 {");

out.println(" text-align: center;");

out.println(" }");

out.println(" .style2 {");

out.println(" text-align: right;");

out.println(" }");

out.println(" </style>");

out.println(" ");

out.println(" <script type=\"text/javascript\">");

out.println(" function myFunc(obj){");

out.println(" var name = document.getElementById('name');");

out.println(" var kor = document.getElementById('kor');");

out.println(" var eng = document.getElementById(\"eng\");");

out.println(" var mat = document.getElementById(\"mat\");");

out.println(" ");

out.println(" var msg = document.getElementById(\"msg\");");

out.println(" msg.style.display = \"none\";");

out.println(" ");

out.println(" //빈칸 검사");

out.println(" if(name.value == \"\" || kor.value == \"\" || eng.value ==\"\"|| mat.value==\"\"){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" } ");

out.println(" //숫자 검사");

out.println(" if (kor.value.match(/[^0-9]/) || eng.value.match(/[^0-9]/)||mat.value.match(/[^0-9]/)){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" } ");

out.println(" //범위 검사");

out.println(" if(parseInt(kor.value)>100 ||parseInt(eng.value)>100 ||parseInt(mat.value)>100 ){");

out.println(" msg.style.display = \"inline\";");

out.println(" return;");

out.println(" }");

out.println(" //데이터 전송");

out.println(" obj.form.submit();");

out.println(" }");

out.println(" </script>");

out.println(" ");

out.println(" </head>");

out.println(" <body>");

out.println(" <div>");

out.println(" <h2>성적 처리</h2>");

out.println(" <form action=\"Oracle08_Insert\" method=\"post\">");

out.println(" 이름 <input type=\"text\" name=\"name\" id=\"name\"><br>"); 

out.println(" 국어 <input type=\"text\" name=\"kor\" id=\"kor\" class=\"subject\"><br>");

out.println(" 영어 <input type=\"text\" name=\"eng\" id=\"eng\" class=\"subject\"><br>");

out.println(" 수학 <input type=\"text\" name=\"mat\" id=\"mat\" class=\"subject\"><br>");

out.println(" <input type=\"button\" value=\" 등록 \"");

out.println(" onclick=\"myFunc(this)\"><br>");

out.println(" <span id=\"msg\" style=\"color:red; display:none;\">이름, 국어, 영어, 수학을 입력해야 합니다.<br>국어, 영어, 수학을 0~100 사이의 숫자를 입력해야 합니다.</span>");

out.println(" </form>");

out.println(" <h3>출력 ------------</h3>");

out.println(" <div>");

out.println(" <table border=\"1\" style=\"width:500px;\">");

out.println(" <tbody>");

out.println(" <tr>");

out.println(" <th>등수</th>");

out.println(" <th>이름</th>");

out.println(" <th>국어</th>");

out.println(" <th>영어</th>");

out.println(" <th>수학</th>");

out.println(" <th>총점</th>");

out.println(" <th>평균</th>");

out.println(" <th>판정</th>");

out.println(" </tr>");

out.println(str);

out.println(" </tbody>");

out.println(" </table>");

out.println(" </div>");

out.println(" </div>");

out.println(" </body>");

out.println(" </html>");

}

}





//Oracle08_Insert.java

package com.test;


import java.io.IOException;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import java.sql.*;


public class Oracle08_Insert 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 {

//한글 출력을 위한 도큐먼트 타입 알려주기

resp.setContentType("text/html; charset=EUC-KR");

req.setCharacterEncoding("euc-kr");

String name = req.getParameter("name");

String kor = req.getParameter("kor");

String eng = req.getParameter("eng");

String mat = req.getParameter("mat");

try {

//데이터베이스 연결 구문

Connection conn = DBConn.getConnection();

//INSERT 실행 구문

String sql = String.format("INSERT INTO score (sid, name, kor, eng, mat) VALUES (scoreSeq.nextval, '%s', %s, %s, %s)", name, kor, eng, mat);

Statement stmt = conn.createStatement();

stmt.executeUpdate(sql);

} catch(Exception e) {

System.out.println(e.toString());

}

//sendRedirect() 메소드 이용

String url = String.format("Oracle08");

resp.sendRedirect(url);

}

}





//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121204</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

 

<servlet>

<servlet-name>oracle08</servlet-name>

<servlet-class>com.test.Oracle08</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>oracle08</servlet-name>

<url-pattern>/Oracle08</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>oracle08_insert</servlet-name>

<servlet-class>com.test.Oracle08_Insert</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>oracle08_insert</servlet-name>

<url-pattern>/Oracle08_Insert</url-pattern>

</servlet-mapping>

</web-app>


-----------------------------------------------------------------------------------------------------


문제) 이름과 전화번호를 저장하는 JDBC 프로그램 작성4. 오라클, Servlet 이용.

데이터 입력과 출력을 동시 실행. 삭제 기능 추가.

MemberDTO, MemberDAO를 별도 작성.


실행 예)

이름 [홍길동        ]

전화번호 [010-123-1234   ]

[ 등록 ]


-----------------------------------

전체 회원수 : 2명

-----------------------------------

회원번호 이름   전화번호      삭제

-----------------------------------

1        홍길동 010-123-1234  삭제

2        김길동 010-222-3333  삭제

-----------------------------------


//DBConn.java


//MemberDTO.java 


//MemberDAO.java 


//Oracle09.java


//Oracle09_Insert.java


//Oracle09_Delete.java



------------------------------------------------------------------------------------------------------

재전송 방법.


1. sendRedirect()

요청주소 -> A

응답주소 -> B

브라우저 -> A -> B


2. forward();

요청주소 -> A (서블릿)

응답주소 -> B (JSP)

브라우저 주소 -> A -> A

'Java > JSP & Servlet' 카테고리의 다른 글

[20121206] 17일차  (0) 2012.12.14
[20121205] 16일차 (JSP / Servlet / JDBC 연동)  (0) 2012.12.05
[20121203] 14일차 (Servlet)  (0) 2012.12.04
[20121122] 8일차 (직원관리 최종버젼)  (0) 2012.12.04
[20121121] 7일차 (직원관리)  (0) 2012.12.04

WRITTEN BY
빨강꼬마

,

이전까지 프로젝트 진행함.

--------------------------------------------------------------------------------



프로젝트 생성 후 환경설정 시작


- DBConn.java

- ojdbc14.jar

- standerd.jer

- jstl.jar



--------------------------------------------------------------------------------

Servlet(서블릿)


1. 서블릿은 Sun사에서 내놓은 웹프로그래밍 언어의 한 종류. Java 언어를 기반으로 동적인 컨텐츠를 생성.


2. Java 코드안에 HTML 코드가 혼재되어 있다.


3. 서블릿은 Servlet 인터페이스를 구현하여 GenericServlet을 만들고 이를 다시

   http 프로토콜에 맞게 확장한 HttpServlet 클래스를 상속한 후 내부 메서드를 재성의(오버라이딩)하여 사용한다.


4. 서블릿의 동작 순서

- 클라이언트의 요청 (서블릿 주소)

- 서블릿 Handler 8080 포트에서 요청 받음.

- 서블릿 컨테이너에서 해당 서블릿 검색

- 해당 서블릿 실행

- 서블릿의 결과인 HTML 도큐먼트를 웹클라이언트에서 출력(웹페이지).


5. Deployment Descripter(배치 기술서)

- 환경 설정 파일.

- web.xml

- 서블릿 맵핑

- 패키지를 포함한 클래스명 과 경로 패턴은 동일할 필요는 없음.

- 서블릿 이름은 위와 아래가 동일해야함.



<servlet>

<servlet-name>서블릿 이름</servlet-name>

<setvlet-class>패키지를 포함한 클래스명</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>서블릿 이름</servlet-name>

<url-pattern>경로 패턴</url-pattern>

</servlet-mapping>


----------------------------------예)

WEB.XML 내 서블릿 맵핑 작업


<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <servlet>

<servlet-name>servlet01</servlet-name>

<servlet-class>com.test.Servlet01</servlet-class>

  </servlet>

  <servlet-mapping>

<servlet-name>servlet01</servlet-name>

    <url-pattern>/Servlet01</url-pattern>

  </servlet-mapping>


</web-app>





* 맵핑을 해야 서블릿 요청이 가능함.

* HttpServlet 클래스를 상속받은 클래스를 서블릿이라 부름.

* doGET, doPOST 가 먼저 호출



WEB.XML에서 서블릿 맵핑후 실제 실행 주소

http://localhost:8090/Servlet_20121203/Servlet01




-----------------------------------------------------------------------

첫 번째 서블릿 클래스 작성


//Servlet01.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet01 extends HttpServlet {

private static final long serialVersionUID = 1L;


//사용자 요청이 GET방식인 경우 자동 호출

//브라우저에 요청한 주소는 GET 방식.

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//HTML 도큐먼트 동적 생성 코드 작성

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<title>");

out.println("</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>Hello, Servlet World!</div>");

out.println("</body>");

out.println("</html>");

}


//사용자 요청이 POST인 경우 자동 호출

//<form action="" method="post"></form> 태그를 이용한 요청

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO Auto-generated method stub

super.doPost(req, resp);

}


}


실행 주소

http://localhost:8090/Servlet_20121203/Servlet01



-----------------------------------------------------------

서블릿과 JSP 비교


//Servlet02.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<%

String str = "Hello, JSP World!";

%>    

<!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>Insert title here</title>

</head>

<body>

<div>

<h3><%=str%></h3>

</div>

</body>

</html>



//eclipse_source\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\Servlet_20121203\org\apache\jsp\Servlet02_jsp.java

//JSP 소스 코드가 서블릿으로 변환된 모습

//Servlet02_jsp.java

package org.apache.jsp;


import javax.servlet.*;

import javax.servlet.http.*;

import javax.servlet.jsp.*;


public final class Servlet02_jsp extends org.apache.jasper.runtime.HttpJspBase

    implements org.apache.jasper.runtime.JspSourceDependent {


  private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();


  private static java.util.List _jspx_dependants;


  private javax.el.ExpressionFactory _el_expressionfactory;

  private org.apache.AnnotationProcessor _jsp_annotationprocessor;


  public Object getDependants() {

    return _jspx_dependants;

  }


  public void _jspInit() {

    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();

    _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());

  }


  public void _jspDestroy() {

  }


  public void _jspService(HttpServletRequest request, HttpServletResponse response)

        throws java.io.IOException, ServletException {


    PageContext pageContext = null;

    HttpSession session = null;

    ServletContext application = null;

    ServletConfig config = null;

    JspWriter out = null;

    Object page = this;

    JspWriter _jspx_out = null;

    PageContext _jspx_page_context = null;



    try {

      response.setContentType("text/html; charset=EUC-KR");

      pageContext = _jspxFactory.getPageContext(this, request, response,

      null, true, 8192, true);

      _jspx_page_context = pageContext;

      application = pageContext.getServletContext();

      config = pageContext.getServletConfig();

      session = pageContext.getSession();

      out = pageContext.getOut();

      _jspx_out = out;


      out.write('\r');

      out.write('\n');


String str = "Hello, JSP World!";


      out.write("    \r\n");

      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");

      out.write("<html>\r\n");

      out.write("<head>\r\n");

      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">\r\n");

      out.write("<title>Insert title here</title>\r\n");

      out.write("</head>\r\n");

      out.write("<body>\r\n");

      out.write("<div>\r\n");

      out.write("\t<h3>");

      out.print(str);

      out.write("</h3>\r\n");

      out.write("</div>\r\n");

      out.write("</body>\r\n");

      out.write("</html>");

    } catch (Throwable t) {

      if (!(t instanceof SkipPageException)){

        out = _jspx_out;

        if (out != null && out.getBufferSize() != 0)

          try { out.clearBuffer(); } catch (java.io.IOException e) {}

        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);

        else log(t.getMessage(), t);

      }

    } finally {

      _jspxFactory.releasePageContext(_jspx_page_context);

    }

  }

}




---------------------------------------------------------------------------------------

문제) 반복문을 이용해서 1~100 사이의 짝수만 출력. Servlet 이용.

* 서블릿 클래스 작성 - HttpServlet 클래스 상속한 클래스

* 서블릿 맵핑 - web.xml - 웹서버 재실행 필요.


---------------------------------------------------------------------------------------

//Servlet03.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet03 extends HttpServlet {


//사용자 요청이 GET방식인 경우 자동 호출

//브라우저에 요청한 주소는 GET 방식.

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

StringBuilder str = new StringBuilder();

for (int a=2; a<=100; a+=2) {

str.append(String.format("%d<br>",a));

}

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


//사용자 요청이 POST인 경우 자동 호출

//<form action="" method="post"></form> 태그를 이용한 요청

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


}



}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Servlet01</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Servlet01</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>servlet03</servlet-name>

<servlet-class>com.test.Servlet03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet03</servlet-name>

<url-pattern>/Servlet03</url-pattern>

</servlet-mapping>


</web-app>



----------------------------------------------------------------

문제) 반복문을 이용해서 1~100 사이의 짝수만 출력. 

마지막에 짝수들의 합까지 출력. JSP 이용.

실행 예)

2

4

6

8

...


100

------

합계:2550



//Servlet04.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Servlet04 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {


StringBuilder str = new StringBuilder();

int sum = 0;


for (int a=1; a<=100; a++) {

if (a%2 == 0) {

str.append(String.format("%d<br>", a));

sum += a;

}

}

str.append(String.format("----------<br>합계: %d", sum));


//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");


}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

// TODO Auto-generated method stub

super.doPost(req, resp);

}


}




-----------

데이터 송수신 테스트1 (텍스트 박스 객체)



//Send01.jsp -> 입력 페이지 역할. 입력된 데이터를 서버로 전송.

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!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>Insert title here</title>

<script type="text/javascript">


function myFunc(obj) {

//데이터 검사

var name = document.getElementById("name");

var tel = document.getElementById("tel");

var msg = document.getElementById("msg");

msg.style.display = "none";

//빈칸 검사

if (name.value == "" || tel.value == "") {

msg.style.display = "inline";

return;

}

//데이터 전송

obj.form.submit();

}


</script>

</head>

<body>

<div>

<h2> 데이터 전송 테스트1</h2>

<!-- action 속성에 서블릿 주소로 표기할 것 -->

<form action="Receive01" method="post">

이름 <input type="text" id="name" name="name"><br>

전화 <input type="text" id="tel" name="tel"><br>

<input type="button" value="전송" onclick="myFunc(this)">

<span id="msg" style="color:red; display:none">데이터 모두 입력해라~</span>

</form>

</div>

</body>

</html>


//Receive01.java -> 처리, 출력 페이지 역할. 클라이언트가 전송한 데이터 수신 및 처리. 결과 메시지를 클라이언트에게 전송.

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive01 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


//송수신 데이터에 한글이 포함된 경우이므로 아래의 명령 추가

req.setCharacterEncoding("euc-kr");

//데이터 수신

String name = req.getParameter("name");

String tel = req.getParameter("tel");

String str = String.format("%s %s", name, tel);

//결과출력

//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트1</h2>");

out.println("<h3>");

out.println(str);

out.println("</h3>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


}



//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>


<servlet>

<servlet-name>receive01</servlet-name>

<servlet-class>com.test.Receive01</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive01</servlet-name>

<url-pattern>/Receive01</url-pattern>

</servlet-mapping>


</web-app>


//요청주소

http://localhost:8090/Servlet_20121203/Send01.jsp


------------------------------------------------------------------------------------------

데이터 송수신 테스트2 

-> Send02, Receive02를 모두 서블릿으로 변경


//Send02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send02 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var name = document.getElementById(\"name\");");

out.println("var tel = document.getElementById(\"tel\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (name.value == \"\" || tel.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트2</h2>");

out.println("<form action=\"Receive02\" method=\"post\">");

out.println("이름 <input type=\"text\" id=\"name\" name=\"name\"><br>");

out.println("전화 <input type=\"text\" id=\"tel\" name=\"tel\"><br>");

out.println("<input type=\"button\" value=\"전송\" onclick=\"myFunc(this)\">");

out.println("<span id=\"msg\" style=\"color:red; display:none\">데이터 모두 입력해라~</span>");

out.println("</form>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


}

}




//Receive02.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive02 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


//송수신 데이터에 한글이 포함된 경우이므로 아래의 명령 추가

req.setCharacterEncoding("euc-kr");

//데이터 수신

String name = req.getParameter("name");

String tel = req.getParameter("tel");

String str = String.format("이름:%s 전화번호:%s", name, tel);

//결과출력

//한글 출력용 인코딩 처리 

resp.setContentType("text/html; charset=EUC-KR");

//HTML 도큐먼트 동적 생성 코드 작성.

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2> 데이터 전송 테스트2</h2>");

out.println("<h3>");

out.println(str);

out.println("</h3>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

 

<servlet>

<servlet-name>send02</servlet-name>

<servlet-class>com.test.Send02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send02</servlet-name>

<url-pattern>/Send02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>receive02</servlet-name>

<servlet-class>com.test.Receive02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive02</servlet-name>

<url-pattern>/Receive02</url-pattern>

</servlet-mapping>


</web-app>



//요청주소

http://localhost:8090/Servlet_20121203/Send02


------------------------------------------------------------------------------------------

문제) 거스름돈을 환폐단위로 구분해서 출력. 서블릿 이용.

실행 예)


금액(10~1000) [990  ]  [결과]


총액 : 990원

오백원 1개, 백원 4개, 오십원 1개, 십원 4개


//Send03.java


//Receive03.java


//web.xml



---------------------------------------

데이터 송수신 테스트3 (라디오 객체)


//Send04.java


//Receive04.java


//web.xml



---------------------------------------

데이터 송수신 테스트4 (체크박스 객체)



//Send05.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send05 extends HttpServlet {


@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 {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("");

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var checkboxes = document.getElementsByName(\"icecream\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("var check = false;");

out.println("for (var a=0; a<checkboxes.length; a++) {");

out.println("if (checkboxes[a].checked) {");

out.println("check = true;");

out.println("}");

out.println("}");

out.println("if (check) {");

out.println("obj.form.submit();");

out.println("} else {");

out.println("msg.style.display = \"inline\";");

out.println("}");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트4</h2>");

out.println("<form action=\"Receive05\" method=\"post\">");

out.println("- 종류 선택 -<br><br>");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"1\"> 고스트월드");     

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"2\"> 엄마는 외계인"); 

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"3\"> 바나나몬스터<br>");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"4\"> 초코라떼크런치 ");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"5\"> 뉴욕치즈케익 ");

out.println("<input type=\"checkbox\" name=\"icecream\" value=\"6\"> 슈팅스타<br>");

out.println("<input type=\"button\" value=\"확인\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">종류를 선택해야 합니다.</span>");

out.println("</form>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


}




//Receive05.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Receive05 extends HttpServlet {

@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 {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String[] array = req.getParameterValues("icecream");

StringBuilder str = new StringBuilder();

String[] icecreamName = {"고스트월드", "엄마는 외계인", "바나나몬스터", "초코라떼크런치", "뉴욕치즈케익", "슈팅스타"};

for (String icecream : array) {

str.append(String.format("<li>%s</li>",icecreamName[Integer.parseInt(icecream)-1]));

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트3</h2>");

out.println("<h3>출력 ------------</h3>");

out.println("<div>선택한 종류는<ol>");

out.println(str);

out.println("</ol>입니다.</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");


}

}




//web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <display-name>Servlet_20121203</display-name>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

    <welcome-file>index.htm</welcome-file>

    <welcome-file>index.jsp</welcome-file>

    <welcome-file>default.html</welcome-file>

    <welcome-file>default.htm</welcome-file>

    <welcome-file>default.jsp</welcome-file>

  </welcome-file-list>

  

  <!-- 서블릿 요청 주소 -->

<servlet>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 서블릿 이름 -->

<servlet-class>com.test.Servlet01</servlet-class>

</servlet>

<!-- 클라이언트 요청 주소 -->

<servlet-mapping>

<!-- 서블릿 매핑용 이름 -->

<servlet-name>servlet01</servlet-name>

<!-- 클라이언트 요청 주소 이름 -->

<url-pattern>/Servlet01</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>servlet03</servlet-name>

<servlet-class>com.test.Servlet03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet03</servlet-name>

<url-pattern>/Servlet03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>servlet04</servlet-name>

<servlet-class>com.test.Servlet04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>servlet04</servlet-name>

<url-pattern>/Servlet04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive01</servlet-name>

<servlet-class>com.test.Receive01</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive01</servlet-name>

<url-pattern>/Receive01</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send02</servlet-name>

<servlet-class>com.test.Send02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send02</servlet-name>

<url-pattern>/Send02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>receive02</servlet-name>

<servlet-class>com.test.Receive02</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive02</servlet-name>

<url-pattern>/Receive02</url-pattern>

</servlet-mapping>


<servlet>

<servlet-name>send03</servlet-name>

<servlet-class>com.test.Send03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send03</servlet-name>

<url-pattern>/Send03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive03</servlet-name>

<servlet-class>com.test.Receive03</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive03</servlet-name>

<url-pattern>/Receive03</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send04</servlet-name>

<servlet-class>com.test.Send04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send04</servlet-name>

<url-pattern>/Send04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive04</servlet-name>

<servlet-class>com.test.Receive04</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive04</servlet-name>

<url-pattern>/Receive04</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>send05</servlet-name>

<servlet-class>com.test.Send05</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>send05</servlet-name>

<url-pattern>/Send05</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>receive05</servlet-name>

<servlet-class>com.test.Receive05</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>receive05</servlet-name>

<url-pattern>/Receive05</url-pattern>

</servlet-mapping>


</web-app>


----------------------------------------------------------------------------------------------

문제) 임의의 수를 입력 받아서 3의 배수, 4의 배수로 구분해서 출력.


실행 예)

임의의 정수(3 또는 4의 배수) [3  ] [결과]


입력받은 숫자 : 3

구분 : 3의 배수



//Send_Receive06.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send_Receive06 extends HttpServlet {


@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}


@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String num = req.getParameter("num");

StringBuilder str = new StringBuilder();

int data = Integer.parseInt(num);

        String s = "3 또는 4의 배수가 아닙니다.";

if ((data % 3) == 0) {

            s = "3의 배수";

        }

if ((data % 4) == 0) {

          s = "4의 배수";

      }

      if ((data % 12) == 0) {

          s = "3 또는 4의 배수";

      }

     

        str.append(String.format("입력 받은 숫자 : %s<br>", num));

       str.append(String.format("구분 : %s<br>", s));        

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println(str);

out.println("</div>");

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}



//web.xml


----------------------------------------------------------------------------------------------------

문제) 임의의 수를 입력 받아서 3의 배수, 4의 배수로 구분해서 출력.


실행 예)

임의의 정수(3 또는 4의 배수) [3  ] [결과]


입력받은 숫자 : 3

구분 : 3의 배수



//Send_Receive06.java

package com.test;


import java.io.IOException;

import java.io.PrintWriter;


import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class Send_Receive07 extends HttpServlet {


@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 {

resp.setContentType("text/html; charset=EUC-KR");

PrintWriter out = resp.getWriter();

String num = req.getParameter("num");

StringBuilder str = new StringBuilder();

if (num == null) {

str.append("");

} else {

int data = Integer.parseInt(num);

        String s = "3 또는 4의 배수가 아닙니다.";

if ((data % 3) == 0) {

            s = "3의 배수";

      }

if ((data % 4) == 0) {

        s = "4의 배수";

      }

      if ((data % 12) == 0) {

          s = "3 또는 4의 배수";

    }

    

        str.append(String.format("입력 받은 숫자 : %s<br>", num));

       str.append(String.format("구분 : %s<br>", s));

}

out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">");

out.println("<html>");

out.println("<head>");

out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=EUC-KR\">");

out.println("<title>Insert title here</title>");

out.println("<script type=\"text/javascript\">");

out.println("function myFunc(obj) {");

out.println("var num = document.getElementById(\"num\");");

out.println("var msg = document.getElementById(\"msg\");");

out.println("msg.style.display = \"none\";");

out.println("if (num.value == \"\") {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("if (num.value.match(/[^0-9]/)) {");

out.println("msg.style.display = \"inline\";");

out.println("return;");

out.println("}");

out.println("obj.form.submit();");

out.println("}");

out.println("</script>");

out.println("</head>");

out.println("<body>");

out.println("<div>");

out.println("<h2>데이터 송수신 테스트5</h2>");

out.println("<form method=\"post\">");

out.println("임의의 정수(3 또는 4의 배수)");

out.println("<input type=\"text\" name=\"num\" id=\"num\"");

out.println("style=\"width:80px;\">");

out.println("<input type=\"button\" value=\"결과\"");

out.println("onclick=\"myFunc(this)\"><br>");

out.println("<span id=\"msg\" style=\"color:red; display:none;\">숫자를 입력해야 합니다.</span>");

out.println("</form>");

out.println("<h3>출력------------</h3>");

out.println("<div>");

out.println("</div>");

out.println(str);

out.println("</div>");

out.println("</body>");

out.println("</html>");

}

}



//web.xml


---------------------------------------------------------------------------------------

문제) 세 개의 숫자를 전달 받아서 그 중에서  가장 큰 숫자, 가장 작은 숫자 구하기. 서블릿 이용.


실행 예)

숫자1 [OO  ]   숫자2 [XX  ]   숫자3 [YY  ]   [결과]


입력 받은 숫자 : OO, XX, YY

가장 큰 숫자 :  OO

가장 작은 숫자 :  YY


//Send_Receive08.java



//web.xml


WRITTEN BY
빨강꼬마

,