Intellij JSP - Cookie Login (쿠키 로그인 예제)
1 minute read
Cookie Login (쿠키 로그인 예제 )
-
Project - CookieLogin
-
home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
String id = "";
for(Cookie c : cookies){
if (c.getName().equals("id")) {
id=c.getValue();
break;
}
}
if(id.isEmpty())
pageContext.include("login.jsp");
else
pageContext.include("user_info.jsp");
%>
<input type="button" value="Get Cookie List" onclick="location.href='cookie_list.jsp'">
</body>
</html>
-
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
<form action="create_cookie.jsp">
<label>ID : <input type="text" name="id"></label><br/>
<label>Password : <input type="text" name="pw"></label><br/>
<input type="submit" value="Login">
</form>
</body>
</html>
-
user_info.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
<%
Cookie[] cookies = request.getCookies();
for(Cookie c : cookies){
if (c.getName().equals("id")) {
out.print(c.getValue() + "님 안녕하세요<br>");
break;
}
}
%>
<input type="button" value="Logout" onclick="location.href='logout.jsp'"><br/><br/>
</body>
</html>
-
create_cookie.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<body>
<%
String id, pw;
id = request.getParameter("id");
pw = request.getParameter("pw");
if (id.equals("qwer") && pw.equals("1234")) {
Cookie cookie = new Cookie("id", id);
cookie.setMaxAge(60);
response.addCookie(cookie);
response.sendRedirect("home.jsp");
} else
%>
<script>
if (!alert('아이디와 비밀번호를 확인해주세요')) document.location = 'home.jsp'
// if (confirm('아이디와 비밀번호를 확인해주세요')) document.location = 'home.jsp'
</script>
</body>
</html>
-
logout.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Logout</title>
</head>
<body>
<%
Cookie cookie = new Cookie("id",null);
cookie.setMaxAge(0);
response.addCookie(cookie);
%>
<script>
if (!alert('로그아웃 되었습니다')) document.location = 'home.jsp'
</script>
</body>
</html>
-
cookie_list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Cookie List</title>
</head>
<body>
<h2>Cookie List</h2><br/>
<hr>
<%
Cookie[] cookies = request.getCookies();
for(Cookie c : cookies){
out.print("Cookie Name : "+c.getName()+"<br>");
out.print("Cookie Value : "+c.getValue()+"<br>");
out.print("<hr>");
}
%>
<input type="button" value="Go Home" onclick="location.href='home.jsp'">
</body>
</html>
-
로그인 (아이디나 비밀번호가 틀릴경우)
-
ID = qwer
-
Password = 1234
-
로그인 성공
-
로그아웃
-
쿠키 리스트
-
Leave a comment