Recent Posts
Recent Comments
Link
06-30 12:53
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

세션을 이용한 로그인 본문

DEV&OPS/Java

세션을 이용한 로그인

ALEPH.GEM 2022. 6. 14. 16:57

로그인 html

프로젝트의 WebContent 폴더 아래에 새 html 파일을 생성하고 이름을 login.html 으로 설정합니다.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인</title>
</head>
<body>
<form action="logProc" method="post">
ID: <input type="text" name="id"><br>
PW: <input type="password" name="pwd"><br>
<input type="submit" value="로그인">
</form>
<p>
<a href="logProc">로그아웃</a>
</body>
</html>

 

로그인/로그아웃 서블릿

작업중인 패키지 경로에 새 서블릿 LoginOut.java 를 생성합니다.

package net.aacii.test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/logProc")
public class LoginOut extends HttpServlet {
	//로그인 처리
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		String id = req.getParameter("id");
		String pwd = req.getParameter("pwd");
		
		if(id.isEmpty() || pwd.isEmpty()) {
			out.print("ID 또는 PW를 입력하세요");
			return;
		}
		HttpSession session = req.getSession();
		if(session.isNew() || session.getAttribute("id") == null) {
			session.setAttribute("id", id);
			out.print("로그인 완료");
		}else {
			out.print("현재 로그인 상태입니다");
		}

		out.close();
	}
	
	//로그아웃 처리
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=UTF-8");
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession(false);
		if(session != null && session.getAttribute("id") != null) {
			session.invalidate();
			out.print("로그 아웃");
		}else {
			out.print("현재 로그 아웃 상태입니다");
		}

		out.close();
	}

}

login.html 에서 로그인 로그아웃을 해보면서 테스트 해보십시오.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90

'DEV&OPS > Java' 카테고리의 다른 글

필터 Filter  (0) 2022.06.15
request 상태 정보 유지  (0) 2022.06.15
세션 Session  (0) 2022.06.14
쿠키 Cookie  (0) 2022.06.14
ServletContext  (0) 2022.06.13