TIL
2025_02_18 TIL
hi_i
2025. 2. 18. 18:23
오늘의 할일
- Servlet과 jpa를 활용한 홈페이지_2
Session 활용
- 로그인 성공시 메인 페이지의 welcome + ID 문구를 나타내기 위한 session활용
- 세션 생성 및 유효시간 설정
- home.jsp 에서 세션의 값이 존재하는지 확인/출력
- 로그인성공 - 로그아웃버튼 및 환영문구
- 로그인x - 로그인 안내 문구/ 버튼
HttpSession session = request.getSession(); //세션 생성
session.setAttribute("id", id);
session.setMaxInactiveInterval(30*60); //30분
--- home.jsp
<%
String userId = (session != null) ? (String) session.getAttribute("id") : null; //세션값 유무에 따른 userId 값 설ㅈ어
%>
if (userId != null) { //세션값 0 ->로그인 성공
%>
<p> //환영문구 + userId
Welcome,
<%=userId%>!
</p> //로그아웃 버튼 활성
<div style="text-align: right; padding-right: 15px;">
<form action="logout" method="post">
<button type="submit" style="border-radius:20px;">Logout</button>
</form>
</div>
<%
} else {
%>
<div> //환영문구 + 로그인 안내문구
<p>Welcome, login or join!</p>
</div> //로그인과 회원가입 버튼 활성
<div style="text-align: right; padding-right: 15px;">
<button type="button" onclick="location.href='/login.jsp'"
style="width: 60px;border-radius:20px;">Login</button>
<button type="button" onclick="" style="width: 60px;border-radius:20px;">join</button>
</div>
<%
}
%>
Cookie 활용
- cookie는 브라우저에 저장되는 형태로 민감한 데이터가 포함되지 않도록 ID값만 저장 후 rememberID에 활용
- 진행순서
- 쿠키생성 -> 체크박스 생성 -> 쿠키값에 따른 input 박스 아이디값 채우기 -> 체크박스 상태(checked)에따라 쿠키 생성/삭제 -> 쿠키값에따라 체크박스 상태 유지 순서로 rememberID(아이디 기억) 구현
//servlet
//로그인 성공
if(request.getParameter("rememberid")!=null) { //체크박스의 체크상태 확인 if
Cookie idCookie = new Cookie("id",id); //쿠키 생성 및 id값 쿠키 저장
idCookie.setMaxAge(60*60);
response.addCookie(idCookie);
request.setAttribute("id", id);
}else {
Cookie idCookie = new Cookie("id", null); // null값의 쿠키 생성
idCookie.setMaxAge(0); // 유지시간 0초 설정 (쿠키삭제)
response.addCookie(idCookie);
}
//jsp
String id =null; //쿠키에서 가져올 id변수 선언/null로 초기화
javax.servlet.http.Cookie[] cookies = request.getCookies(); //쿠키값을 담을 쿠키배열생성
if (cookies != null) {
for (javax.servlet.http.Cookie cookie : cookies) { //쿠키배열을 돌면서
if ("id".equals(cookie.getName())) { //쿠키이름이 id인 값 찾기
id = cookie.getValue(); // 쿠키 값 가져오기
break;
}
}
}
<input type="checkbox" name="rememberid"
<%= id!=null?"checked='checked'":"" %>value = "true"> //input checkbox의 체크값을 쿠키 존재여부로 상태변경