잡동사니에도 사랑을

[21.10.08] MVC활용(2) - 로그인(mvcmember) 본문

JAVA_EE/MVC

[21.10.08] MVC활용(2) - 로그인(mvcmember)

luvforjunk 2021. 10. 11. 00:37
728x90
반응형

저번 회원가입 창 구현에 이어 로그인 창 구현 작업을 진행해보려 한다.

 

그림을 통해 그 순서를 알아보자.

 

  1. loginForm.jsp에서 로그인을 수행한다.
  2. 로그인 버튼을 누르면 ControlServlet으로 로그인을 해달라는 요청이 간다.
  3. properties 확장자 파일로 넘어와 URL요청에 따른 클래스 위치를 찾아낸다. (/member/loginForm.do = URL요청)

- URL을 설정하게 되면 요청한 URL주소(http://localhost:8080/member/loginForm.do)로 접근해야 접속이 가능하다. 

 

   4. 다시 Servlet으로 넘어온 뒤 로그인을 수행하는 LoginService.java로부터 데이터를 가져오고, DB에 접속하고, 그에 따른 응답을 한다.

   5. 로그인 성공 시 loginOK.jsp, 로그인 실패 시 loginFail.jsp로 return한다.(return값 = 최종적으로 보여질 페이지)

 

 

 

////////loginForm.jsp

더보기

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
<style type="text/css">
div {
color: red;
font-size: 8pt;
font-weight: bold;
}
</style>
</head>
<body>
<form name="loginForm" method="post" action="http://localhost:8080/mvcmember/member/login.do">
<table border="1" cellspacing="0" cellpadding="5">
<tr>
<td width="100" align="center">아이디</td>
<td>
<input type="text" name="id" id="id" placeholder="아이디 입력">
<div id= "idDiv"></div>
</td>
</tr>

<tr>
<td width="100" align="center">비밀번호</td>
<td>
<input type="password" name="pwd" id="pwd" size="30" placeholder="비밀번호 입력">
<div id= "pwdDiv"></div>
</td>
</tr>

<tr>
<td colspan="2" align="center">
<input type="button" id="loginBtn" value="로그인">
<input type="button" value="회원가입" onclick="location.href='writeForm.do'">
</td>
</tr>
</table>
</form>

<script type="text/javascript" src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="../js/member.js"></script>
</body>
</html>

 

 

 

////////ControlServlet.java

더보기

package com.control;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ControlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
    
private Map<String, Object> map = new HashMap<String, Object>();

//최초실행
public void init(ServletConfig config) {
String propertyConfig = config.getInitParameter("propertyConfig");
System.out.println("propertyConfig = "+propertyConfig+"\n");

FileInputStream fin = null;
Properties properties = new Properties();

try {
fin = new FileInputStream(propertyConfig);
properties.load(fin);
System.out.println("properties = "+properties);

} catch (IOException e) {
e.printStackTrace();
}finally{
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println();

Iterator it = properties.keySet().iterator();
while(it.hasNext()) {
String key = (String)it.next();
System.out.println("key = "+key);

String className = properties.getProperty(key);
System.out.println("className = "+className);

try {
Class<?> classType = Class.forName(className);
Object ob = classType.newInstance();

System.out.println("ob = "+ob);

map.put(key, ob);

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();


System.out.println();
}//while

}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     execute(request, response);
    }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}

protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println();

//한글처리
if(request.getMethod().equals("POST")) {
request.setCharacterEncoding("UTF-8");
}

//http://localhost:8080/mvcmember/member/writeForm.do 요청
String category = request.getServletPath(); // -> /member/writeForm.do
System.out.println("category = "+category);

CommandProcess commandProcess = (CommandProcess)map.get(category);
System.out.println("commandProcess = "+commandProcess);

String view = null;
try {
view = commandProcess.requestPro(request, response); //메소드 요청
} catch (Throwable e) {
e.printStackTrace();
}

//forward
RequestDispatcher dispatcher = request.getRequestDispatcher(view);//상대번지
dispatcher.forward(request, response);//제어권 넘기기
}
}

 

 

 

////////command.properties

더보기

#로그인
/member/loginForm.do=member.service.LoginFormService
/member/login.do=member.service.LoginService
/member/logout.do=member.service.LogoutService

 

 

 

////////LoginFormService.java

package member.service;

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

import com.control.CommandProcess;

public class LoginFormService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		return "/member/loginForm.jsp";
	}
}

 

 

 

////////LoginService.java

package member.service;

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

import com.control.CommandProcess;

import member.dao.MemberDAO;

public class LoginService implements CommandProcess {

	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		//데이터
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
		
		//DB
		MemberDAO memberDAO = MemberDAO.getInstance();
		String name = memberDAO.login(id, pwd);
		
		//응답
		if(name==null) {
			return "/member/loginFail.jsp";
		}else {
			//쿠키
			/*
			 * Cookie cookie = new Cookie("memName", name); //쿠키 생성 
			 * cookie.setMaxAge(30*60); // 초 단위 
			 * //cookie.setPath("/"); - 만약 URL을 /member/로 지정하면 member폴더로 쿠키를 전송하라는 의미 
			 * response.addCookie(cookie); //클라이언트로 보내기
			 * 
			 * Cookie cookie2 = new Cookie("memId", id); //쿠키 생성 
			 * cookie2.setMaxAge(30*60); //초 단위 
			 * //cookie2.setPath("/"); response.addCookie(cookie2); //클라이언트로 보내기
			 */			
			//세션 - Tomcat에다 저장. 경로 지정 필요없음
			HttpSession session = request.getSession(); // 세션 생성
			session.setAttribute("memName", name);
			session.setAttribute("memId", id);
			
			//request.setAttribute("name", name);
			return "/member/loginOk.jsp";
		}
	}
}

*주요내용

→ 쿠키와 세션

https://devuna.tistory.com/23
 

[web] 쿠키(cookie)와 세션(session)의 개념/차이/용도/작동방식

[web] 쿠키(cookie)와 세션(session)의 개념/차이/용도/작동 쿠키와 세션을 이해하기 위해서는 먼저 http의 특징에 대해 이해하면 도움이 됩니다. 비연결성(Connectionless) HTTP(Hypertext Transfer Protocol..

devuna.tistory.com

 

 

////////LogoutService.java

package member.service;

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

import com.control.CommandProcess;

public class LogoutService implements CommandProcess{
	
	@Override
	public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable {
		
		HttpSession session = request.getSession();
		
		// 세션 - 특정 세션 제거
		session.removeAttribute("memName");
		session.removeAttribute("memId");
		
		//모든 세션 제거
		session.invalidate();
		
		//응답
		return "/member/logout.jsp";
	}
}

 

 

 

////////loginOk.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
String name = null;
String id = null;

//쿠키
/* Cookie[] ar = request.getCookies(); //모든 쿠키를 다 꺼내와야 한다
if(ar != null) {
	for(int i=0; i<ar.length; i++){
		String cookieName = ar[i].getName(); // 쿠키명
		String cookieValue = ar[i].getValue(); //값
		
		System.out.println("쿠키명 = " + cookieName);
		System.out.println("값 = " + cookieValue);

		if(cookieName.equals("memName")) name = cookieValue;
		if(cookieName.equals("memId")) id = cookieValue;
	}//for
}//if */

//세션
//name = (String)session.getAttribute("memName");
//id = (String)session.getAttribute("memId");
%>    
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
img {
	width: 70px;
	height: 50px;
	cursor: pointer; /* 화살표가 나오는 걸 손가락으로 나오게 하기 위해 */
}
</style>
</head>
<body>
<%-- <%=name %>님 로그인 --%>

<img src="../img/img5.PNG" onclick="location.href='../index.jsp'">
%{sessionScope.memName}님 로그인
<br><br>
<input type="button" value="로그아웃" onclick="location.href='/mvcmember/member/logout.do'">
</body>
</html>

 

 

 

////////loginFail.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>아이디 또는 비밀번호가 맞지 않습니다</h3>
</body>
</html>

 

 

 

////////logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<%
/* //쿠키
Cookie[] ar = request.getCookies(); //모든 쿠키를 다 꺼내와야 한다
if (ar != null) {
	for (int i = 0; i < ar.length; i++) {
		if(ar[i].getName().equals("memName")) {
			ar[i].setMaxAge(0); // 쿠키 삭제
			ar[i].setPath("/");
			response.addCookie(ar[i]); // 클라이언트에게 보내기
			
		}
		
		if(ar[i].getName().equals("memId")) {
			ar[i].setMaxAge(0); // 쿠키 삭제
			ar[i].setPath("/");
			response.addCookie(ar[i]); // 클라이언트에게 보내기
		}
	}
} */

//세션 - 특정 세션 제거
//session.removeAttribute("memName");
//session.removeAttribute("memId");

//세션 - 모든 세션 제거
//session.invalidate(); //무효화
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>로그아웃</h3>

<script type="text/javascript">
window.onload=function() {
	alert("로그아웃");
	location.href="../index.jsp";
}
</script>
</body>
</html>

 

 

 

////////MemberDAO.java

더보기

package member.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import member.bean.MemberDTO;

public class MemberDAO {
private Connection conn=null;
private PreparedStatement pstmt;
private ResultSet rs;

private DataSource ds;

private static MemberDAO instance = null;

public static MemberDAO getInstance() {
if(instance == null) {
synchronized (MemberDAO.class) {
instance = new MemberDAO();//생성
}
}

return instance;
}

public MemberDAO() {
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle"); //Tomcat의 경우

} catch (NamingException e) {
e.printStackTrace();
}
}

public void write(MemberDTO memberDTO) {
String sql = "insert into member values(?,?,?,?,?,?,?,?,?,?,?,?,sysdate)";

try {
conn = ds.getConnection();

pstmt = conn.prepareStatement(sql);//생성
pstmt.setString(1, memberDTO.getName());
pstmt.setString(2, memberDTO.getId());
pstmt.setString(3, memberDTO.getPwd());
pstmt.setString(4, memberDTO.getGender());
pstmt.setString(5, memberDTO.getEmail1());
pstmt.setString(6, memberDTO.getEmail2());
pstmt.setString(7, memberDTO.getTel1());
pstmt.setString(8, memberDTO.getTel2());
pstmt.setString(9, memberDTO.getTel3());
pstmt.setString(10, memberDTO.getZipcode());
pstmt.setString(11, memberDTO.getAddr1());
pstmt.setString(12, memberDTO.getAddr2());

pstmt.executeUpdate();//실행

} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

public String login(String id, String pwd) {
String name = null;
String sql = "select * from member where id=? and pwd=?";

try {
conn = ds.getConnection();

pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);

rs = pstmt.executeQuery();//실행

if(rs.next()) name = rs.getString("name");

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

return name;
}

public boolean isCheckId(String id) {
boolean exist = false;
String sql = "select * from member where id=?";

try {
conn = ds.getConnection();

pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);

rs = pstmt.executeQuery();

if(rs.next()) exist = true;

} catch (SQLException e) {
e.printStackTrace();
}

return exist;
}

}

 

 

 

////////MemberDTO.java

더보기

package member.bean;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class MemberDTO {
private String name;
private String id;
private String pwd;
private String gender;
private String email1;
private String email2;
private String tel1;
private String tel2;
private String tel3;
private String zipcode;
private String addr1;
private String addr2;

}

*주요내용

→ DTO는 이전과 마찬가지로 lombok.jar를 이용하여 Getter와 Setter를 대신해준다.

 

 

 

728x90
반응형