본문 바로가기

안녕하세요!

프로그래밍 언어/JSP

JSP_22-11-14

[ pom.xml ]

○ ajax 비동기 연동

      <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
	  <dependency>
		  <groupId>com.fasterxml.jackson.core</groupId>
		  <artifactId>jackson-databind</artifactId>
		  <version>2.13.4.2</version>
	  </dependency>
      
      <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
	  <dependency>
		  <groupId>com.fasterxml.jackson.core</groupId>
		  <artifactId>jackson-core</artifactId>
		  <version>2.13.4</version>
	  </dependency>

 

[ registerAjax.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"	uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt"	uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%	request.setCharacterEncoding("UTF-8"); %>

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>회원 가입 (AJAX)</title>
</head>
<body>

<!-- 메뉴바 -->
<jsp:include page="../common/topMenu.jsp" flush="false"/>

<h1 align="center">회원 가입(AJAX)</h1>

<div class="container">
	<form class="form-horizontal" method="post" action="${contextPath}/member/register">
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-6">
				<h2 align="center">회원 가입(실시간 아이디 검사)</h2>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">아 이 디</label>
			<div class="col-sm-2">
				<input type="text" class="form-control" id="id" name="name" maxlength="20" placeholder="Enter ID"/>
			</div>
			<div class="col-sm-2">
				<button class="idCheck btn btn-warning" type="button" id="idCheck" onClick="fn_idCheck();" value="N">아이디 중복확인</button>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">비밀번호</label>
			<div class="col-sm-3">
				<input type="password" class="form-control" id="pwd" name="pwd" maxlength="20" placeholder="Enter PASSWORD"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">이  름</label>
			<div class="col-sm-4">
				<input type="text" class="form-control" id="name" name="name" maxlength="50" placeholder="Enter NAME"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-2 control-label">이메일</label>
			<div class="col-sm-4">
				<input type="email" class="form-control" id="email" name="email" maxlength="50" placeholder="Enter Email"/>
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button type="reset"  class="btn btn-warning">입력취소</button>
				<button type="button" class="btn btn-danger cancel">회원가입 취소</button>
				<button type="submit" class="btn btn-success" id="submit">회원가입</button>
				<button type="submit" class="btn btn-primary signUpBtn"  disabled="disabled">회원가입</button>
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<input type="text" class="form-control msg" name="msg" placeholder="Message" id="msg"/>
			</div>
			<div id="msg2"></div>
		</div>
	
	</form>



</div>

</body>

<script>
function fn_idCheck() {
	// alert($("#id").val());
	$.ajax({
		url:		"/member/idCheck",
		type:		"post",
		dataType:	"json",
		data:		{"id" : $("#id").val()},
		success:	function(data) {
			if(data == 1) {
				alert("이미 사용 중인 아이디입니다.\n\n다른 아이디를 입력하십시오.");
			} else if(data == 0) {
				// 버튼 id="idCheck"의 속성인 value의 값을 "Y"로 변경한다.
				$("#idCheck").attr("value", "Y");	
				alert("사용 가능한 아이디입니다.");
			}
		}
	});
}
</script>
<script>
$(document).ready(function() {
	// 취소 버튼이 눌렸을 경우 로그인 화면으로 이동한다.
	$(".cancel").on("click", function() {
		location.href = "/member/loginForm.do";
	});

	// 회원가입 버튼을 눌렀을 경우
	$("#submit").on("click", function() {
		// alert("회원가입 버튼을 누르셨습니다.");
		if($("#id").val() == "") {
			alert("아이디를 입력하셔야 합니다.");
			$("#id").focus();
			return false;
		}
		if($("#id").val().length < 4) {
			alert("아이디는 최소 4자리를 입력하셔야 합니다.");
			$("#id").focus();
			return false;
		}
		if($("#pwd").val() == "") {
			alert("비밀번호를 입력하셔야 합니다.");
			$("#pwd").focus();
			return false;
		}
		if($("#name").val() == "") {
			alert("이름을 입력하셔야 합니다.");
			$("#name").focus();
			return false;
		}
		if($("#email").val() == "") {
			alert("이메일을 입력하셔야 합니다.");
			$("#email").focus();
			return false;
		}
	});

	// 아이디 입력란에 글자를 입력하면 실시간으로 사용가능한 아이디 인지 아닌지 검사한다.
	$("#id").on("input", function() {
		// alert("글자를 입력하셨습니다. => " + $("#id").val());
		
		// 입력된 글자의 값을 변수에 저장한다.
		let inputID = $("#id").val();

		// 입력한 아이디가 서버에 존재하는 지 알아낸다.
		$.ajax({
			url:		"/member/idCheck",
			type:		"post",
			dataType:	"json",
			data:		{"id" : $("#id").val()},
			success:	function(data) {
				if(inputID == "" && data == '0') {
					$(".signUpBtn").prop("disabled", true);
					$(".signUpBtn").css("background-color", "#AAAAAA");
					$("#idCheck").css("background-color", "#FFCECE");
					document.getElementById("msg2").innerHTML = "아이디를 입력하십시오.";
					document.getElementById("msg").value = "아이디를 입력하십시오.";
				} else if(inputID != "" && data == '0' && inputID.length >= 4) {
					$("#idCheck").css("background-color", "#B0F6AC");
					document.getElementById("msg2").innerHTML = "사용이 가능한 아이디입니다.";
					document.getElementById("msg").value = "사용이 가능한 아이디입니다.";
					$("#msg").css("background-color", "#B0F6AC");
					$(".signUpBtn").prop("disabled", false);
					$(".signUpBtn").css("background-color", "#4CAF50");
				} else if(data == '1') {
					$(".signUpBtn").prop("disabled", true);
					$(".signUpBtn").css("background-color", "#AAAAAA");
					$("#idCheck").css("background-color", "#FFCECE");
					document.getElementById("msg2").innerHTML = "이미 사용 중인 아이디입니다.";
					document.getElementById("msg").value = "이미 사용 중인 아이디입니다.";
					$("#msg").css("color", "#FFFFFF");
					$("#msg").css("background-color", "#FF3F80");
				}
			}
		});
		
		
	});
	
});

</script>


</html>

 

[ LoginModalForm.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link href="../../bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<title>Manager Login</title>
	<style>
	.modal-header, h4, .close {
		background-color:	#5CB85C;
		color:				white !important;
		text-align:			center;
		font-size:			30px;
	}
	.modal-footer {
		background-color:	#F9F9F9;
	}
	</style>
</head>
<body>
<div class="container">
	<h2>Manager Login</h2>
	<!-- Trigger the modal with a button -->
	<button type="button" class="btn btn-warning btn-lg" id="myBtn">Login</button>

	<!-- Modal -->
	<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
		aria-labelledby="myModalLabel" aria-hidden="true">
		<div class="modal-dialog">

			<!-- Modal content -->		
			<div class="modal-content">
				<div class="modal-header" style="padding: 35px 50px;">
					<button type="button" class="close" data-dismiss="modal">&times;</button>
					<h4><span class="glyphicon glyphicon-lock"></span> Manager Login</h4>
				</div>
				<div class="modal-body" style="padding: 40px 50px;">
					<form class="form-horizontal" role="form" method="post" 
						action="managerLoginPro.jsp">
						<div class="form-group">
							<label for="username"><span class="glyphicon glyphicon-user">
								</span> Manager ID</label>
							<input type="text" class="form-control" id="id" name="id" maxlength="10"
								placeholder="Enter Admin ID"/>
						</div>
						<div class="form-group">
							<label for="pwd"><span class="glyphicon glyphicon-eye-open">
								</span> Password</label>
							<input type="password" class="form-control" id="pwd" name="passwd"
								maxlength="10" placeholder="Enter Password"/>
						</div>
						<button type="submit" class="btn btn-success btn-block">
							<span class="glyphicon glyphicon-off"></span> Login
						</button>
					</form>
				</div>
				<div class="modal-footer">
					<button type="submit" class="btn btn-danger pull-flef" data-dismiss="modal">
						<span class="glyphicon glyphicon-remove"></span> Cancel
					</button>
				</div>
			</div>
		</div>
	</div>


</div>

	<script src="../../js/jquery-3.5.1.min.js"></script>
	<script src="../../bootstrap/js/bootstrap.min.js"></script>
	<script>
	$(document).ready(function() {
		$("#myBtn").click(function() {
			$("#myModal").modal();
		});
	});
	</script>
	<script>
	$(function() {
		$('#myModal').modal({
			keyboard:	true
		});
	});
	</script>
</body>
</html>

 

[ loginForm.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"	uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<c:set var="result"		 value="${param.result}"/>
<%	request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>로그인 화면</title>
	
<c:choose>	
	<c:when test="${result == 'loginFailed'}">
		<script>
		window.onload = function() {
			alert("\n아이디를 잘못 입력하셨습니다.\n\n다시 로그인을 해주세요!");
		}
		</script>
	</c:when>
	<c:when test="${result == 'PasswordFailed'}">
		<script>
		window.onload = function() {
			alert("\n비밀번호를 잘못 입력하셨습니다.\n\n다시 로그인을 해주세요!");
		}
		</script>
	</c:when>
</c:choose>
	
</head>
<body>

<div class="container">
	<form class="form-horizontal" method="post" action="${contextPath}/member/login.do">
		<div class="form-group">
			<div class="col-sm-offset-4 col-sm-3">
				<h2 align="center">로그인</h2>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-offset-3 col-sm-2 control-label">아이디</label>
			<div class="col-sm-2">
				<input type="text" class="form-control" id="id" name="id" maxlength="10" placeholder="아이디"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-offset-3 col-sm-2 control-label">비밀번호</label>
			<div class="col-sm-2">
				<input type="password" class="form-control" id="pwd" name="pwd" maxlength="20" placeholder="비밀번호"/>
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-5 col-sm-2">
				<button type="reset"	class="btn btn-warning">다시입력</button>
				<button type="submit"	class="btn btn-primary">로그인</button>
			</div>
		</div>
	</form>
</div>

</body>
</html>

 

[ updateMemberFrom.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c"	uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt"	uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%	request.setCharacterEncoding("UTF-8"); %>
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>회원 정보 수정</title>
</head>
<body>

<!-- 메뉴바 -->
<jsp:include page="../common/topMenu.jsp" flush="false"/>
	
<div class="container">
	<form class="form-horizontal" method="post" name="memModifyForm" action="${contextPath}/member/modifyMember.do">
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-5">
				<h2 align="center">회원 정보 수정</h2>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-3 control-label">아이디</label>
			<div class="col-sm-2">
				<input type="text" class="form-control" id="id" name="id" maxlength="10" value="${member.id}" readonly/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-3 control-label">비밀번호</label>
			<div class="col-sm-3">
				<input type="password" class="form-control" id="pwd" name="pwd" maxlength="20" value="${member.pwd}"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-3 control-label">비밀번호 확인</label>
			<div class="col-sm-3">
				<input type="password" class="form-control" id="repwd" name="repwd" maxlength="20" value="${member.pwd}"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-3 control-label">이  름</label>
			<div class="col-sm-3">
				<input type="text" class="form-control" id="name" name="name" maxlength="50" value="${member.name}"/>
			</div>
		</div>
		<div class="form-group">
			<label for="id" class="col-sm-3 control-label">이메일</label>
			<div class="col-sm-5">
				<input type="text" class="form-control" id="email" name="email" maxlength="50" value="${member.email}"/>
			</div>
		</div>
		<div class="form-group">
			<div class="col-sm-offset-3 col-sm-4">
				<button type="reset"  class="btn btn-warning">다시 입력</button>
				<button type="submit" class="btn btn-primary">회원 정보 수정</button>
			</div>
		</div>
	</form>
</div>
	
<!-- 푸터 -->
<jsp:include page="../common/footer.jsp" flush="false"/>
	
</body>
</html>

 

[ topMenu.jsp ]

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%	request.setCharacterEncoding("UTF-8"); %>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>	

<%	/*
	sticky-top은 상단 공간을 차지하면서 위에 고정하고,
	fixed-top은 상단 공간을 차지하지 않고 위에 고정된다.
	일부 내용이 상단 메뉴바에 가려져서 보이지 않을 수 있다.
	*/
%>
<nav class="navbar navbar-inverse navbar-sticky-top">
	<div class="container-fluid">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="${contextPath}/main.do">쇼핑몰</a>
		</div>
		<!-- 실질적인 메뉴를 나열한다. -->
		<div class="collapse navbar-collapse" id="myNavbar">
			<ul class="nav navbar-nav navbar-left">
				<li>
					<form class="navbar-form navbar-right" method="post" action="${contextPath}/member/login.do">
						<c:choose>
							<c:when test="${isLogOn == true && member != null}">
								<p class="navbar-text"><b>${member.name}님, 즐거운 시간되십시요.</b></p>
								<a href="${contextPath}/member/logout.do" class="btn btn-danger">
								<span class="glyphicon glyphicon-log-out"></span> 로그아웃</a>
							</c:when>
							<c:otherwise>
								<div class="form-group">
									<input type="text"     class="form-control" name="id"  size="12" maxlength="12" placeholder="아이디"/>
									<input type="password" class="form-control" name="pwd" size="12" maxlength="12" placeholder="비밀번호"/>
								</div>
								<button type="submit" class="btn btn-primary">
									<span class="glyphicon glyphicon-log-in"></span> 로그인
								</button>
							</c:otherwise>
						</c:choose>
					</form>
				</li>
				<li class="dropdown">
					<a class="dropdown-toggle" data-toggle="dropdown" href="#">회원관리 <span class="caret"></span></a>
					<ul class="dropdown-menu">
						<li><a href="${contextPath}/member/loginForm.do?">로그인</a></li>
						<li><a href="${contextPath}/member/memberForm.do">회원가입</a></li>
						<li><a href="${contextPath}/member/registerAjaxForm.do">회원가입(AJAX)</a></li>
						<li><a href="${contextPath}/member/listMembers.do">회원 목록 조회</a></li>
					</ul>
				</li>
			</ul>
		</div>
	</div>
</nav>

 

[ memberMapper.xml ]

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
   "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.edu.member">

	<resultMap id = "memberResult" type="com.edu.member.vo.MemberVO">
		<result property="id"			column="id"/>
		<result property="pwd"			column="pwd"/>
		<result property="name"			column="name"/>
		<result property="email"		column="email"/>
		<result property="joinDate"		column="joinDate"/>
	</resultMap>

	<!-- 로그인 처리 -->
	<select id="loginByID" parameterType="com.edu.member.vo.MemberVO" resultMap="memberResult">
		<![CDATA[
			SELECT	*
			FROM	T_MEMBER
			WHERE	ID = #{id}
		]]>
	</select>
	
	<!-- 회원가입 처리 -->
	<insert id="addMember" parameterType="com.edu.member.vo.MemberVO">
		<![CDATA[
			INSERT INTO T_MEMBER (id, pwd, name, email, joindate)
			VALUES (#{id}, #{pwd}, #{name}, #{email}, sysdate())
		]]>
	</insert>
	
	<!-- 회원 전체 목록 추출하기 -->
	<select id="selecAllMemberList" resultMap="memberResult">
		<![CDATA[
			SELECT * FROM T_MEMBER ORDER BY JOINDATE DESC
		]]>
	</select>

	<!-- 아이디에 해당하는 회원 정보 가져오기 -->
	<select id="selectMember" parameterType="String" resultType="com.edu.member.vo.MemberVO">
		<![CDATA[
		SELECT * FROM t_member WHERE id = #{id}
		]]>
	</select>
	
	<!-- 아이디에 해당하는 회원 정보 수정하기 -->
	<update id="updateMember" parameterType="com.edu.member.vo.MemberVO">
		<![CDATA[
		UPDATE 	t_member
		SET		pwd = #{pwd}, name = #{name}, email = #{email}
		WHERE	id = #{id}
		]]>
	</update>
	
	<!-- 아이디에 해당하는 회원 정보 삭제하기 -->
	<delete id="deleteMember" parameterType="String">
		<![CDATA[
		DELETE	FROM t_member
		WHERE	id = #{id}
		]]>
	</delete>
	
	<!-- 아이디 중복 검사 : 입력한 아이디가 존재하는지 알아낸다. -->
	<select id="idCheck" parameterType="com.edu.member.vo.MemberVO" resultType="int">
		<![CDATA[
		SELECT	COUNT(*) 
		FROM	t_member
		WHERE	id = #{id}
		]]>
	</select>

   
</mapper>

 

[ MemberController.java ]

package com.edu.member.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.edu.member.vo.MemberVO;

//-------------------------------------------------------------------------------------
// public interface MemberController
//-------------------------------------------------------------------------------------
public interface MemberController {

	//-----------------------------------------------------------------------------------------------------------
	// 로그인 처리
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView login(@ModelAttribute("member") MemberVO member, RedirectAttributes rAttr,
			HttpServletRequest request, HttpServletResponse response) throws Exception;

	//-----------------------------------------------------------------------------------------------------------
	// 로그아웃 처리
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 회원가입 폼
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView memberForm(HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 회원가입 처리
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView addMember(@ModelAttribute("member") MemberVO memberVO,
			HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 회원 전체 목록 조회
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView listMembers(HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 조회
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView updateMemberForm(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView modifyMember(@ModelAttribute("info") MemberVO memberVO,
				HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	public ModelAndView removeMember(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response) throws Exception;

	//-------------------------------------------------------------------------------------
	// 회원 가입 화면 불러오기 (AJAX)
	//-------------------------------------------------------------------------------------
	public String getRegisterAjaxForm() throws Exception;
	
	//-------------------------------------------------------------------------------------
	// 아이디 중복 검사 (AJAX)
	//-------------------------------------------------------------------------------------
	public int idCheck(MemberVO memberVO) throws Exception;
	
	
	
} // End - public interface MemberController

 

[ MemberControllerImpl.java ]

package com.edu.member.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.edu.member.service.MemberService;
import com.edu.member.vo.MemberVO;

//-------------------------------------------------------------------------------------
// public class MemberControllerImpl implements MemberController
//-------------------------------------------------------------------------------------
@Service
@Controller
@RequestMapping("/member") // url에서 /member로 시작하는 요청들을 처리한느 컨트롤러
public class MemberControllerImpl implements MemberController {

	private static final Logger logger = LoggerFactory.getLogger(MemberControllerImpl.class);
	
	//-------------------------------------------------------------------------------------
	// @Inject 	  : Java에서 지원하는 어노테이션, 특정 Framework에 종속적이지 않다.
	// @Autowired : Spring에서 지원하는 어노테이션
	//-------------------------------------------------------------------------------------
	@Autowired
	private MemberVO memberVO;
	
	// private MemberService memberService = new MemberService();
	@Autowired
	private MemberService memberService;
	
	//-------------------------------------------------------------------------------------
	// 로그인 처리
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public ModelAndView login(@ModelAttribute("member") MemberVO member, RedirectAttributes rAttr, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		logger.info("MemberControllImpl login() 시작......");
		System.out.println("로그인 정보 => " + member.getId() + " : " + member.getPwd());
		
		ModelAndView mav = new ModelAndView();
		
		// 로그인한 정보를 가지고 데이터베이스에 존재하는지 처리를 하고 그 결과를 가져온다.
		memberVO = memberService.login(member);
		System.out.println("로그인 처리 결과 ==> " + memberVO);
		
		// 로그인한 정보가 데이터베이스에 존재하는지에 따라 처리를 다르게 한다.
		if(memberVO != null) { // 로그인 정보에 해당하는 자료가 있으면
			
			
			if(member.getPwd().equals(memberVO.getPwd())) {
				// 아이디와 비밀번호가 일치하면 세션을 발급한다.
				HttpSession session = request.getSession();
				session.setAttribute("member", memberVO);
				session.setAttribute("isLogOn", true);
				// mav.setViewName("redirect:/member/listMembers.do");
				mav.setViewName("redirect:/main.do");	// 메인화면으로 이동
				
				
			} else { // 아이디는 있지만 비밀번호가 틀린 경우
				rAttr.addAttribute("result", "PasswordFailed");
				mav.setViewName("redirect:/member/loginForm.do");
			}
			
			
		} else { // 로그인한 아이디가 존재하지 않으면
			// 로그인 실패 메시지를 가지고 로그인화면으로 이동한다.
			rAttr.addAttribute("result", "loginFailed");
			mav.setViewName("redirect:/member/loginForm.do");
		}
		return mav;	
	} // End - 로그인 처리

	
	//-------------------------------------------------------------------------------------
	// 로그아웃 처리
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = "/logout.do", method = RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request ,HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		session.removeAttribute("member");
		session.removeAttribute("isLogOn");
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("redirect:/main.do"); // 메인 화면으로 이동
		return mav;
	} // End - 로그아웃 처리
	
	
	//-------------------------------------------------------------------------------------
	// 회원가입 폼
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = "/memberForm.do", method = RequestMethod.GET)
	public ModelAndView memberForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/member/memberForm"); // 회원가입 화면으로 이동
		return mav;
		
	} // End - 회원가입 폼

	
	//-------------------------------------------------------------------------------------
	// 회원가입 처리
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = "/addMember.do", method=RequestMethod.POST)
	public ModelAndView addMember(@ModelAttribute("memberVO") MemberVO memberVO, 
		   HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		logger.info("MemberControllImpl 회원가입 처리() 시작......");

		request.setCharacterEncoding("UTF-8");
		response.setContentType("test/html;charset=UTF-8");
		
		int result = 0;
		// 사용자가 입력한 정보를 서비스에게 넘겨주어 처리하게 된다.
		result = memberService.addMember(memberVO);
		
		ModelAndView mav = new ModelAndView("redirect:/member/listMembers.do");
		
		return mav;
	} // End - 회원가입 처리

	//-------------------------------------------------------------------------------------
	// 회원 전체 목록 조회
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value = "/listMembers.do", method=RequestMethod.GET)
	public ModelAndView listMembers(HttpServletRequest request, HttpServletResponse response) throws Exception {

		logger.info("MemberControllImpl 회원 전체 목록 조회() 시작......");

		// 회원 전체 목록을 가져온다.
		List<MemberVO> memberLists = memberService.listMembers();
		
		ModelAndView mav = new ModelAndView("/member/listMembers");
		mav.addObject("memberLists", memberLists);
		
		return mav;
	} // End - 회원 전체 목록 조회
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 조회
	//-----------------------------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value="/updateMemberForm.do", method=RequestMethod.GET)
	public ModelAndView updateMemberForm(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		System.out.println("MemberController 회원 정보 조회 id ==> " + id);
		
		// 회원 전체 리스트 화면에서 수정을 요청한 id에 해당하는 정보를 찾는 일을 서비스에게 부탁한다.
		memberVO = memberService.selectMember(id);
		System.out.println("MemberController 회원 정보 조회 ==> " + memberVO);
		
		// 찾아온 데이터를 가지고 개인 정보 수정화면으로 넘어간다.
		ModelAndView mav = new ModelAndView("/member/updateMemberForm");
		mav.addObject("member", memberVO);
		
		return mav;
	} // End - 아이디에 해당하는 회원 정보 조회

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value="modifyMember.do", method=RequestMethod.POST)
	public ModelAndView modifyMember(@ModelAttribute("memberVO") MemberVO memberVO, HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		System.out.println("MemberController 회원 정보 수정하기 memberVO ==> " + memberVO);
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		int result = memberService.modifyMember(memberVO);

		ModelAndView mav = new ModelAndView("redirect:/member/listMembers.do");
		return mav;
	} // End - 아이디에 해당하는 회원 정보 수정하기

	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value="removeMember.do", method=RequestMethod.GET)
	public ModelAndView removeMember(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		int result = memberService.removeMember(id);
		
		ModelAndView mav = new ModelAndView("redirect:/member/listMembers.do");
		return mav;
	} // End - 아이디에 해당하는 회원 정보 삭제하기

	
	//-------------------------------------------------------------------------------------
	// 회원 가입 화면 불러오기 (AJAX)
	//-------------------------------------------------------------------------------------
	@Override
	@RequestMapping(value="/registerAjaxForm.do", method=RequestMethod.GET)
	public String getRegisterAjaxForm() throws Exception {

		System.out.println("MemberController 회원 가입 화면 불러오기 (AJAX) ==> ");
		
		
		return "/member/registerAjax";
	} // End - 회원 가입 화면 불러오기 (AJAX)


	//-------------------------------------------------------------------------------------
	// 로그인 중복 검사 (AJAX) : 비동기 통신 방법 사용
	//-------------------------------------------------------------------------------------
	@Override
	@ResponseBody
	@RequestMapping(value="/idCheck", method=RequestMethod.POST)
	public int idCheck(MemberVO memberVO) throws Exception {

		System.out.println("MemberController 아이디 중복 검사(AJAX) id ==> " + memberVO.getId());
		
		int result = memberService.idCheck(memberVO);
		System.out.println("result : " + result);
		return result;
	} // End - 로그인 중복 검사 (AJAX)

	
	
} // End - public class MemberControllerImpl implements MemberController

 

[ MemberService.java ]

package com.edu.member.service;

import java.util.List;

import org.springframework.dao.DataAccessException;

import com.edu.member.vo.MemberVO;

//-----------------------------------------------------------------------------------------------------------
// 회원정보 서비스
//-----------------------------------------------------------------------------------------------------------
public interface MemberService {

	//-----------------------------------------------------------------------------------------------------------
	// 로그인 처리
	//-----------------------------------------------------------------------------------------------------------
	public MemberVO login(MemberVO memberVO) throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 회원가입 처리
	//-----------------------------------------------------------------------------------------------------------
	public int addMember(MemberVO memberVO) throws DataAccessException;
	
	//-----------------------------------------------------------------------------------------------------------
	// 회원 전체 목록 가져오기
	//-----------------------------------------------------------------------------------------------------------
	public List<MemberVO> listMembers() throws DataAccessException;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 가져오기
	//-----------------------------------------------------------------------------------------------------------
	public MemberVO selectMember(String id) throws DataAccessException;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	public int modifyMember(MemberVO memberVO) throws DataAccessException;
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	public int removeMember(String id) throws DataAccessException;
	

	//-------------------------------------------------------------------------------------
	// 아이디 중복 검사 (AJAX)
	//-------------------------------------------------------------------------------------
	public int idCheck(MemberVO memberVO) throws DataAccessException;

	
	
	

} // End - public interface MemberService

 

[ MemberServiceImpl.java ]

package com.edu.member.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.edu.member.vo.MemberVO;
import com.edu.member.dao.MemberDAO;

//-----------------------------------------------------------------------------------------------------------
//회원정보 서비스
//-----------------------------------------------------------------------------------------------------------
@Service("memberService")
public class MemberServiceImpl implements MemberService {

	private static final Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);
	
	@Autowired
	private MemberDAO memberDAO;
	
	//-----------------------------------------------------------------------------------------------------------
	// 로그인 처리
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public MemberVO login(MemberVO memberVO) throws DataAccessException {

		logger.info("MemberServiceImpl login() 시작.....");
		return memberDAO.loginByID(memberVO);
		
	}

	//-----------------------------------------------------------------------------------------------------------
	// 회원가입 처리
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int addMember(MemberVO memberVO) throws DataAccessException {

		logger.info("MemberServiceImpl 회원가입 처리() 시작....." + memberVO);
		return memberDAO.addMember(memberVO);
		
	} // End - 회원가입 처리

	//-----------------------------------------------------------------------------------------------------------
	// 회원 전체 목록 가져오기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public List<MemberVO> listMembers() throws DataAccessException {

		logger.info("MemberServiceImpl 회원 전체 목록 가져오기() 시작.....");
		List<MemberVO> memberLists = null;
		memberLists = memberDAO.selectAllMemberList();
		return memberLists;
		
	} // End - 회원 전체 목록 가져오기

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 가져오기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public MemberVO selectMember(String id) throws DataAccessException {
		MemberVO memberVO = memberDAO.selectMember(id);
		return memberVO;
	}

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int modifyMember(MemberVO memberVO) throws DataAccessException {
		return memberDAO.updateMember(memberVO);
	}

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int removeMember(String id) throws DataAccessException {
		return memberDAO.deleteMember(id);
	}
	

	//-------------------------------------------------------------------------------------
	// 아이디 중복 검사 (AJAX)
	//-------------------------------------------------------------------------------------
	@Override
	public int idCheck(MemberVO memberVO) throws DataAccessException {

		logger.info("MemberServiceImpl 아이디 중복 검사 (AJAX) 시작.....");

		int result = memberDAO.idCheck(memberVO);
		
		return result;
	}





} // End - public class MemberServiceImpl implements MemberService

 

[ MemberDAO.java ]

package com.edu.member.dao;

import java.util.List;

import org.springframework.dao.DataAccessException;

import com.edu.member.vo.MemberVO;

//-------------------------------------------------------------------------------------
// 회원정보 DAO
//-------------------------------------------------------------------------------------
public interface MemberDAO {

	//-----------------------------------------------------------------------------------------------------------
	// 로그인 처리
	//-----------------------------------------------------------------------------------------------------------
	public MemberVO loginByID(MemberVO memberVO) throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 회원 가입 처리
	//-----------------------------------------------------------------------------------------------------------
	public int addMember(MemberVO memberVO) throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 회원 전체 목록 가져오기
	//-----------------------------------------------------------------------------------------------------------
	public List<MemberVO> selectAllMemberList() throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 가져오기
	//-----------------------------------------------------------------------------------------------------------
	public MemberVO selectMember(String id) throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	public int updateMember(MemberVO memberVO) throws DataAccessException;

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	public int deleteMember(String id) throws DataAccessException;
	

	
	//-------------------------------------------------------------------------------------
	// 아이디 중복 검사 (AJAX)
	//-------------------------------------------------------------------------------------
	public int idCheck(MemberVO memberVO) throws DataAccessException;

	
	
	
} // End - public interface MemberDAO

 

[ MemberDAOImpl.java ]

package com.edu.member.dao;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import com.edu.member.vo.MemberVO;

//-----------------------------------------------------------------------------------------------------------
// 회원정보 DAO
//-----------------------------------------------------------------------------------------------------------
@Repository("memberDAO")
public class MemberDAOImpl implements MemberDAO {

	@Autowired
	private SqlSession sqlSession;
	
	private static final Logger logger = LoggerFactory.getLogger(MemberDAOImpl.class);

	private static final String Namespace = "com.edu.member";
	
	//-----------------------------------------------------------------------------------------------------------
	// 로그인 처리
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public MemberVO loginByID(MemberVO memberVO) throws DataAccessException {

		MemberVO memVO = sqlSession.selectOne(Namespace + ".loginByID", memberVO);
		return memVO;
		
	} // End - 로그인 처리

	//-----------------------------------------------------------------------------------------------------------
	// 회원가입 처리
	// sqlSession.insert(사용할 mapper의 id, DB에 저장할 값)
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int addMember(MemberVO memberVO) throws DataAccessException {

		logger.info("MemberDAOImpl 회원가입 처리() 시작....." + memberVO);
		
		int result = sqlSession.insert(Namespace + ".addMember", memberVO);
		return result;
		
	} // End - 회원가입 처리

	//-----------------------------------------------------------------------------------------------------------
	// 회원 전체 목록 가져오기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public List<MemberVO> selectAllMemberList() throws DataAccessException {

		logger.info("MemberDAOImpl 회원 전체 목록 가져오기() 시작.....");

		List<MemberVO> memberLists = null;
		memberLists = sqlSession.selectList(Namespace + ".selecAllMemberList");
		return memberLists;
		
	} // End - 회원 전체 목록 가져오기
	
	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 가져오기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public MemberVO selectMember(String id) throws DataAccessException {
		MemberVO memberVO = sqlSession.selectOne(Namespace + ".selectMember", id);
		return memberVO;
	}

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 수정하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int updateMember(MemberVO memberVO) throws DataAccessException {
		int result = sqlSession.update(Namespace + ".updateMember", memberVO);
		return result;
	}

	//-----------------------------------------------------------------------------------------------------------
	// 아이디에 해당하는 회원 정보 삭제하기
	//-----------------------------------------------------------------------------------------------------------
	@Override
	public int deleteMember(String id) throws DataAccessException {
		int result = sqlSession.delete(Namespace + ".deleteMember", id);
		return result;
	}
	

	//-------------------------------------------------------------------------------------
	// 아이디 중복 검사 (AJAX)
	//-------------------------------------------------------------------------------------
	@Override
	public int idCheck(MemberVO memberVO) throws DataAccessException {

		logger.info("MemberDAOImpl idCheck(MemberVO memberVO) id : " + memberVO.getId());

		return sqlSession.selectOne(Namespace + ".idCheck", memberVO); // 같은 값이 나오지 않도록 selectOne 설정
		
		 
	} // End - 아이디 중복 검사 (AJAX)
	


	

}

 

728x90
반응형

'프로그래밍 언어 > JSP' 카테고리의 다른 글

JSP_22-11-15  (2) 2022.11.15
JSP_22-11-07  (0) 2022.11.15
JSP_22-11-11(2)  (0) 2022.11.11
JSP_22-11-11  (0) 2022.11.11

loading