JSP
[JSP] 30. JSP와 세션을 사용해 로그인 과정 만들어보기
Song hyun
2024. 7. 4. 11:49
728x90
반응형
[JSP] 30. JSP와 세션을 사용해 로그인 과정 만들어보기
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 페이지</title>
</head>
<body>
<h2>로그인</h2>
<!-- 로그인 처리는 예외적인 사항으로 post 요청을 한다 -->
<form action="welcome.jsp" method="get">
<label for="username">username : </label>
<input type="text" id="username" name="username" value="홍길동">
<label for="password">password : </label>
<input type="password" id="password" name="password" value="1234">
<button type="submit">로그인</button>
</form>
</body>
</html>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>환영해요~</title>
</head>
<body>
<%
// http://localhost:8080/jsp/welcome.jsp
// session 객체를 사용하여 사용자 정보가 있는지, 여부를 확인하자.
String username=(String)session.getAttribute("username");
if(username==null || username.trim().isEmpty()){
// request 객체에서 사용자 정보를 추출하자.
username=request.getParameter("username");
if(username!=null && !username.trim().isEmpty()){
// 홍길동이라면 okay
// 하지만 ""라면 통과 x (!username.trim().isEmpty())
// 세션 객체를 사용해서 사용자 정보를 저장(속성과 값을)
session.setAttribute("username", username);
} else{
// 사용자가 정상적인 데이터를 보내지 않았다면
response.sendRedirect("login.jsp");
return;
}
}
// application 내장 객체를 사용하여 방문 횟수 증가
Integer visitCount=(Integer) application.getAttribute("visitCount");
if(visitCount==null){
visitCount=1;
} else {
visitCount++;
}
Date now=new Date();
%>
<h2>환영 합니다, <%= username %></h2>
<p>현재 시간 : <%= now %></p>
<p>방문 횟수 : <%= visitCount %></p>
</body>
</html>
728x90
반응형