login.jsp (로그인 화면)
<%@page import="org.apache.jasper.tagplugins.jstl.core.ForEach"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 페이지</title>
</head>
<body>
<%
String saveId = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie c : cookies) {
if (c.getName().equals("memberId")) {
saveId = c.getValue();
}
}
}
%>
<form action="loginProc" method="post">
<%
if (saveId != null) {
%>
id : <input type="text" name="mId" value="<%=saveId%>">
<%
} else {
%>
id : <input type="text" name="mId" value="">
<%
}
%>
pw : <input type="text" name="mPw">
<div>
rememberMe <input type="checkbox" name="isSaveId">
</div>
<input type="submit" value="login">
</form>
</body>
</html>
home.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>
<%
Cookie[] cookies = request.getCookies();
String userId = "";
if (cookies != null) {
for (Cookie c : cookies) {
System.out.print("c name " + c.getName());
System.out.print("c age " + c.getMaxAge());
if (c.getName().equals("memberId")) {
userId = c.getValue();
}
}
}
%>
<h1>
여기는
<%=userId%>
홈 화면 입니다.
</h1>
버튼 생성 -> 쿠키 삭제하기 기능 추가
</body>
</html>
LoginProc.java (서블릿)
package com.boot.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/loginProc")
public class LoginProc extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginProc() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String mId = request.getParameter("mId");
String mPw = request.getParameter("mPw");
Cookie[] cookies = request.getCookies();
Cookie serverCookie = null;
//check -> on , not check -> null
String isSaveId = request.getParameter("isSaveId");
if (isSaveId == null) {
System.out.println("isSaveId " + isSaveId);
for (Cookie c : cookies) {
System.out.println("c name " + c.getName());
// memberId --> 시간을 0으로 돌리고 다시 response 에 담아 준다.
c.setMaxAge(0); // 초단위 : 0으로 하면 삭제 효과
response.addCookie(c);
}
} else {
// 쿠키 저장 코드 why ( 기억하라고 허락했음)
serverCookie = new Cookie("memberId", mId);
response.addCookie(serverCookie);
}
response.sendRedirect("home.jsp");
}
}
'개발일지 > JSP' 카테고리의 다른 글
DAO & DTO (0) | 2022.11.29 |
---|---|
JSP - MYSQL 연결 (0) | 2022.11.28 |
Servlet JSP 스크립트 (0) | 2022.11.24 |
Servlet form 데이터 처리 (0) | 2022.11.24 |
Servlet Life-Cycle(서블릿 생명주기) (0) | 2022.11.24 |
댓글