2 분 소요

로그인 로직 만들기


DB에 user의 정보를 등록하고 user의 ID와 Password를 가져다 클라이언트에서 입력한 user의 ID와 Password가 일치하는지 확인하고 일치한다면 로그인을 유지하는 로직을 만들어보자.

****

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String userid = null;
	String name = null;
	String idx = null;
	if(session.getAttribute("userid") != null){
		userid = (String)session.getAttribute("userid");
		name = (String)session.getAttribute("name");
		idx = (String)session.getAttribute("idx");
	}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>
	<h2>로그인</h2>
<%
	if(userid == null){
%>
	<form method="post" action="login_ok.jsp">
		<p>아이디 : <input type="text" name="userid"></p>
		<p>비밀번호 : <input type="password" name="userpw"></p>
		<p><input type="submit" value="로그인"></p>
		<p>회원이 아니신가요? <a href='./2_member.jsp'>회원가입</a></p>
	</form>
<%
	}else{
%>
	<h3><%=userid%>(<%=name%>)님 환영합니다.</h3>
	<p>
		<input type="button" value="정보수정" onclick="location.href='info.jsp'">
		<input type="button" value="로그아웃" onclick="location.href='logout.jsp'">
	</p>
<%
	}
%>
</body>
</html>

위 코드는 로그인을 할 수 있는 form를 만들고 form에 post 방식으로 입력한 userid, userpw가 ID와 PW를 분석해 처리해줄 2_login_ok.jsp로 보내지게된다.


****

<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String userid = request.getParameter("userid"); // apple
	String userpw = request.getParameter("userpw"); // 1111
	
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	String sql = "";
	String url = "jdbc:mysql://localhost:3306/aiclass";
	String uid = "root";
	String upw = "1234";

	try {
		Class.forName("com.mysql.cj.jdbc.Driver");
		conn = DriverManager.getConnection(url, uid, upw);
		if (conn != null) {
			sql = "select mem_idx, mem_name from tb_member where mem_userid=? and mem_userpw=?";
			pstmt = conn.prepareStatement(sql); // 컴파일
			pstmt.setString(1, userid);
			pstmt.setString(2, userpw);
			rs = pstmt.executeQuery();
			if(rs.next()){
				session.setAttribute("userid", userid);
				session.setAttribute("idx", rs.getString("mem_idx"));
				session.setAttribute("name", rs.getString("mem_name"));
%>
			<script>
				alert('로그인되었습니다.');
				location.href="login.jsp";
			</script>
<%
			}else{ // 로그인 실패
%>	
			<script>
				alert('아이디 또는 비밀번호를 확인하세요');
				history.back();
			</script>
<%
			}
		}	
	} catch (Exception e) {
		e.printStackTrace();
}
%>	

이제 2_login.jsp에서 받아온 userid, userpw를 파라미터로 받아 DB에서 검색을 하게된다.

여기서 SQL문을 보게되면,

select mem_idx, mem_name from tb_member where mem_userid=? and mem_userpw=?
// tb_member 테이블에서 mem_userid uesrid이고 mem_userpw userpw 
// 조건을 만족하는 레코드 중에 mem_idx mem_name 데이터를 가져오라는 의미

이 조건을 만족한다면

if(rs.next()){
    session.setAttribute("userid", userid);
    session.setAttribute("idx", rs.getString("mem_idx"));
    session.setAttribute("name", rs.getString("mem_name"));

여기에서 DB에서 받은 값들로 세션을 생성해준다.

그리고 2_login.jsp으로 이동하게되고, 만약 DB에 만족하는 데이터가 없었다면 history.back(); 원래 있던 페이지로 돌아는 것을 의미한다.

다시 2_login.jsp를 다시보면 상단 코드에서 세션을 받게된다.

if(session.getAttribute("userid") != null){
    userid = (String)session.getAttribute("userid");
    name = (String)session.getAttribute("name");
    idx = (String)session.getAttribute("idx");
}

만약 세션 이름이 userid 인 세션이 존재하지 않는다면(로그인 실패 시), form 양식을 다시 보여주게되고 세션이 존재한다면

<h3><%=userid%>(<%=name%>)님 환영합니다.</h3>
<p>
    <input type="button" value="정보수정" onclick="location.href='info.jsp'">
    <input type="button" value="로그아웃" onclick="location.href='logout.jsp'">
</p>

이와 같은 html 양식을 보여주게된다.

이때 로그아웃를 누를 시,


<2_logout.jsp 전체 코드>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	session.invalidate();
%>
<script>
	alert('로그아웃 되었습니다');
	location.href='login.jsp';
</script>

이 페이지로 이동하여 존재하는 세션을 제거하고 다시 2_login.jsp로 이동하게된다.


결과 확인

로그인 페이지
jsp7_1

로그인완료 페이지
jsp7_2

태그:

카테고리:

업데이트: