728x90
반응형
✔ 내장객체
✔ JSP 내장 객체
❗ request 객체
웹 브라우저의 요청 정보를 저장하고 있는 객체
메소드
getHeader() : 요청 정보의 헤더를 반환
getMethod() : 요청 정보의 http method(get, post) 반환
getParameter() : 요청 정보의 이름(name)으로 요청 값(value)을 반환
getParameterValues() : 요청 정보의 이름으로 요청 값을 배열로 반환
setCharacterEncoding() : 요청 정보의 인코딩을 설정
❗ response 객체
웹 브라우저의 요청에 대한 응답 정보를 저장하고 있는 객체
✔ 쿠키
🔏 쿠키(cookie)
- 프로그램에서 흔적을 남기는 것. 클라이언트와 서버가 연결을 시도한 흔적을 남겼다가,
후에 또 연결을 시도할 시 과거의 접속을 이어나가기 위해 흔적을 사용하는 방법.
- 클라이언트에 정보를 저장, 클라이언트 측에서 윈도우나 프로그램을 제거하면 서버가 인지 X
- 클라이언트에 저장하므로 서버의 부하를 줄일 수 있지만 보안상 취약(누구나 확인가능)
- 데이터의 저장이 1.2MB로 제한(문자로 저장)
- 텍스트 데이터만 저장
🔏 쿠키를 생성하는 방법
Cookie 객체명 = new Cookie("키", "값");
🔏 쿠키 시간 설정
setMaxAge() : 쿠키가 유지되는 시간을 설정(초)
setMaxAge(60 * 60 * 24 * 30); // 30일
60초에 60분에 24시간에 30일
🔏 쿠키를 클라이언트에게 전달하는 방법
response.addCooki(쿠키객체);
🔏 쿠키를 서버에서 읽어오는 방법
Cookie[] 배열명 = request.getCookie();
✔ 쿠키 예제 1
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import = "java.net.URLEncoder" %>
<%
Cookie cookie1 = new Cookie("userid", "apple");
Cookie cookie2 = new Cookie("name", "김사과");
cookie1.setMaxAge(180);
cookie2.setMaxAge(180);
/* 시간이 지나면 쿠키 삭제(3분) */
response.addCookie(cookie1);
response.addCookie(cookie2);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키</title>
</head>
<body>
<h2>쿠키</h2>
<p>쿠키가 정상적으로 설정되었습니다.</p>
</body>
</html>
✔ 쿠키 예제 2
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키 읽기</title>
</head>
<body>
<h2>쿠키 읽기</h2>
<%
for(Cookie cookie : cookies){
out.println(cookie.getName() + ":" + cookie.getValue()+ "<br>");
}
%>
</body>
</html>
✔ 쿠키 로그인 메인 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies();
String userid = null; /* nullPointException에 대비하기 위해 */
if(cookies != null){
for(Cookie cookie : cookies){/* 여러 쿠키가 담겨있을것을 예상하여 */
if("userid".equals(cookie.getName())){
userid = cookie.getValue();
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠키로 구현한 로그인</title>
</head>
<body>
<h2>쿠키로 구현한 로그인</h2>
<%
if(userid == null){
%>
<form method ="post" action="3_login_ok.jsp">
<p>아이디 : <input type ="text" name ="userid"></p>
<p>비밀번호 : <input type ="password" name ="userpw"></p>
<p><button>login</button></p>
</form>
<%
}else{
%>
<h3><%=userid %>님 환영합니다!!!!!!</h3>
<p><a href ="3_logout.jsp">로그아웃</a></p>
<!-- 기존에 같은 값으로 덮어씌우면 쿠키값을 없는것처럼 할 수 있고 아니면 시간을 0 또는 마이너스로 -->
<%
}
%>
</body>
</html>
✔ 쿠키 로그인 구현 부 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
if(userid.equals("apple") && userpw.equals("1234")){
//login
Cookie cookie = new Cookie("userid",userid);
cookie.setMaxAge(60*10);
response.addCookie(cookie);
%>
<script>
alert('로그인 되었습니다.')
location.href = "3_login.jsp";
//refresh - 데이터가 갱신이됨, 새로운 페이지를 가지고 오며 캐시가 날라간다.
</script>
<%
}else{
//login X
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요.')
history.back();
// 캐시가 남는다 -> 캐시에 있는 정보를 가지고 앞, 뒤로 이동 한다.
</script>
<%
}
%>
✔ 쿠키 로그아웃 구현부 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
Cookie[] cookies = request.getCookies(); /* 쿠키불러오기 */
if(cookies != null){
for(Cookie cookie : cookies){
if("userid".equals(cookie.getName())){
Cookie newCookie = new Cookie("userid","");
newCookie.setMaxAge(0);
response.addCookie(newCookie);
}
}
}
%>
<script>
alert('로그아웃 되었습니다.')
location.href = '3_login.jsp';
</script>
✔ 세션
✔ 세션(session)
- 서버에 사용자 정보를 저장
- 서버상에 존재하는 객체로 브라우저 단위당 1개씩 존재
- 쿠키에 비하여 보안이 좋음
- 웹브라우저를 닫기 전까지 유지
🔏 세션변수 만들기
session.setAttribute("변수명", "값");
🔏 세션변수 값 읽어오기
session.getAttribute("변수명");
🔏 세션변수 삭제하기
session.invalidate();
🔏 세션 아이디 가져오기
session.getId()
🔏 세션 아이디 시간설정
- 톰켓 web.xml (분딘위 세션 시간을 설정)
<session-config>
<session-timeout>30</session-timeout>
</session-config>
sendRedirect() : 클라이언트를 원하는 페이지로 이동
✔ 세션 예제1
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.setAttribute("userid", "apple");
// B0974869CBE0B908661BE62D3F74CDFA -> userid(apple)
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>session</title>
</head>
<body>
<h2>session</h2>
<p>session id: <%=session.getId() %></p>
</body>
</html>
✔ 세션 예제2
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}else{
userid = "아이디 없음";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션 읽어오기</title>
</head>
<body>
<h2>세션 읽어오기</h2>
<p>세션 아이디 : <%=session.getId() %></p>
<p>세션 변수(아이디) : <%=userid %></p>
</body>
</html>
✔ 세션 로그인 메인 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = null;
if(session.getAttribute("userid") != null){
userid = (String)session.getAttribute("userid");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>세션으로 구현한 로그인</title>
</head>
<body>
<h2>세션으로 구현한 로그인</h2>
<%
if(userid ==null){
%>
<form method ="post" action="6_login_ok.jsp">
<p>아이디 : <input type ="text" name ="userid"></p>
<p>비밀번호 : <input type ="password" name ="userpw"></p>
<p><button>login</button></p>
</form>
<%
}else{
%>
<h3><%=userid %>님 환영합니다.</h3>
<p><a
href ="6_logout.jsp">로그아웃</a></p>
<!-- 기존에 같은 값으로 덮어씌우면 쿠키값을 없는것처럼 할 수 있고 아니면 시간을 0 또는 마이너스로 -->
<%
}
%>
</body>
</html>
✔ 세션 로그인 로그인 부분 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
if(userid.equals("apple") && userpw.equals("1234")){
//login 성공!
session.setAttribute("userid",userid);
%>
<script>
alert('로그인 되었습니다.')
location.href = "6_login.jsp";
//refresh - 데이터가 갱신이됨, 새로운 페이지를 가지고 오며 캐시가 날라간다.
</script>
<%
}else{
//login 실패!
%>
<script>
alert('아이디 또는 비밀번호를 확인하세요.')
history.back();
// 캐시가 남는다 -> 캐시에 있는 정보를 가지고 앞, 뒤로 이동 한다.
</script>
<%
}
%>
✔ 세션 로그인 로그아웃 부분 예제
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
%>
<script>
alert('로그아웃 되었습니다.')
location.href = '6_login.jsp';
</script>
반응형
'JSP' 카테고리의 다른 글
JSP (예외, pagecontext, ajax, XMLHttpRequest) (0) | 2022.11.21 |
---|---|
JSP (서블릿, 세션, 장바구니) (0) | 2022.11.21 |
JSP 데이터 요청 (get, post) 방식 (0) | 2022.11.18 |
JSP (장단점, 기본 문법) (0) | 2022.11.17 |
JSP 사용 전 사전 지식(Tomacat, Eclipse 초기 설정 등) (0) | 2022.11.17 |