------------------------------------------------
상담 게시판 패스워드 변경 (사용자)
//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}
'Java > JSP & Servlet' 카테고리의 다른 글
[20121213] 22일차 (상담게시판) (0) | 2012.12.18 |
---|---|
[20121212] 21일차 (상담게시판) (0) | 2012.12.18 |
[20121211] 20일차 (상담게시판) (0) | 2012.12.18 |
[20121210] 19일차 (상담게시판) (0) | 2012.12.18 |
[20121207] 18일차 (상담게시판) (0) | 2012.12.18 |
WRITTEN BY