50일차 22.11.30
REQUEST 객체 QUIZ02
<%@ 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>
<%--
1. form태그를 이용해서 post형식으로 이름, 키와 몸무게를 입력받음
2. req_quiz_02_ok.jsp로 전송
3. 해당 페이지에서는 넘어간 값을 BMI지수로 처리
4. BMI공식 = kg / (cm/100 * cm/100) -> 문자열이기 때문에 형변환 진행(실수)
화면에 이름, 키, 몸무게 BMI지수를 출력
if를 통해 BMI지수가 25 이상 과체중, 18 이하라면 저체중, 나머지는 정상으로 출력
--%>
<form action="req_quiz_ok02.jsp" method="post" >
<h3>사람</h3>
<br>
이름: <input type = "text" name="name"><br>
키: <input type = "text" name="height"><br>
몸무게: <input type = "text" name="weight"><br>
<input type="submit" name="submit" value = "확인">
</form>
</body>
</html>
결과창>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");//post
String name = request.getParameter("name");
String height = request.getParameter("height");
String weight = request.getParameter("weight");
double bmi = Double.parseDouble(weight) /
((Double.parseDouble(height)/100) * (Double.parseDouble(height)/100));
String bmis = "";
if(bmi >= 25){
bmis = "과체중";
}else if(bmi <= 18){
bmis = "저체중";
}else{
bmis = "정상";
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=name %><br>
키 : <%=height %><br>
몸무게 : <%=weight %><br>
BMI지수 : <%=bmi %><br>
<%=name %>은(는) <%=bmis %> 입니다.<br>
</body>
</html>
REQUEST 객체 QUIZ02
<%@ 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>
<h3>req_quiz03.jsp</h3>
<p>다음을 구현하고 a태그 클릭시 req_quiz_ok03에 학생번호를 출력하세요</p>
<%for(int i = 1; i <= 100; i++){%>
<a href="req_quiz_ok03.jsp?num=<%=i %>" >
<%=i %>번 학생
</a> <br>
<%}
%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");//post
String num = request.getParameter("num");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=num %> 번 학생 선택
</body>
</html>
*response 객체
- 웹 브라우저의 요청에 응답하는 것을 response라고 한다
- 이러한 응답의 정보를 가지고 있는 객체를 response객체라고 함
<%@ 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>
<form action="res_ex01_result.jsp" method="post">
이름: <input type="text" name="name"><br>
나이: <input type="text" name="age"><br>
<input type="submit" value="확인"><br>
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");//한글처리
String name = request.getParameter("name");
String age = request.getParameter("age");
//age에 따라 다른 결과 페이지로 이동
int result = Integer.parseInt(age);
if(result >= 20){
response.sendRedirect("res_ex01_ok.jsp");
}else{
response.sendRedirect("res_ex01_no.jsp");
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
<%@ 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>
ok페이지
</body>
</html>
<%@ 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>
no페이지
더 크고 오너라
</body>
</html>
<%@ 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>
<style>
.container {
display: flex;
height: 100vh;
background-color: #81F7F3;
justify-content: center;
align-items: center;
}
#wrap {
border: 1px solid #777;
background-color: #ffffff;
padding: 10px;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<!--
태그의 class 속성 - 태그를 식별하는 이름(화면에서 중복O)
주로 디자인을 적용하는 데 사용
선택자 class는 .으로, id는 #으로 지칭해서 나타냄
태그의 id - 고유하게 식별하는 이름(화면에서 중복이 있으면 X)
-->
<form action="res_ex02_result.jsp" method="post" id="wrap">
아이디: <input type="text" name="id" placeholder="아이디"><br>
비밀번호: <input type="password" name="pw" placeholder="비밀번호"><br>
<input type="submit" value="로그인"><br>
</form>
</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");//한글처리
String id = request.getParameter("id");
String pw = request.getParameter("pw");
/*
1. id, pw를 받아서 처리합니다
2. id가 abc1234이고 비밀번호가 asd123이라면 로그인 성공으로 간주하고 res_ex02_ok로 리다이렉트
3. id or pw가 틀린경우 res_ex02_no로 리다이렉트
*/
if(id.equals("abc1234") && pw.equals("asd123")){
response.sendRedirect("res_ex02_ok.jsp");
}else{
response.sendRedirect("res_ex02_no.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>
로그인 성공
</body>
</html>
<%@ 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>
로그인 실패
</body>
</html>
*쿠키(cookie)
- 웹 브라우저에서 서버로 데이터를 요청하면, 서버측에서는 알맞은 로직 수행 후 데이터를 부라우저에 응답한다
- 응답 후에는 웹브라우저와의 관계를 종료한다
- 이때, 정보를 지속적으로 유지하기 위한 수단 -> 쿠키
ex) 로그인 후 장바구니에 담기, 이후 주문, 결제를 한다고 했을 때
장바구니, 주문, 결제 페이지 이동할 때마다 연결이 끊김-> 정보를 계속 유지하기 위한 수단 -> 쿠키
- 쿠키와 반대로 계속 연결을 걸어놓고 있는 수단 -> 소켓
- 쿠키는 만료시간이 존재(만료시간까지 계속해서 저장됨) -> setter메서드로 설정 -> 클라이언트(브라우저)에 보냄(저장)
- 쿠키는 전부 문자열로 표현
* cookie 객체 관련 메서드
- setMaxAge() : 쿠키의 유효시간(만료시간) 설정
-getName() : 쿠키 이름 얻는 메서드
-getValue() : 쿠키 값 얻는 메서드
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//쿠키는 서버에서 생성해서 response에 담아서 클라이언트로 보냅니다
//1. 쿠키 생성문
Cookie idCookie = new Cookie("user_id", "kkk123");//이름 , 값
Cookie nameCookie = new Cookie("user_name", "홍길동");//이름 , 값
//2. 쿠키 시간 설정
idCookie.setMaxAge(3600);//시간
nameCookie.setMaxAge(30);//30초
//3. 쿠키를 response에 저장
response.addCookie(idCookie);
response.addCookie(nameCookie);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="cookie_ex01_ok.jsp">쿠키 확인하기</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//쿠키 확인하기
//브라우저에 쿠키는 request객체에 자동으로 넘어와서 저장됩니다.(만료 전까지 어디서든 사용가능)
Cookie[] cookies = request.getCookies();
//쿠기가 없다면 null이기 때문에 에러 발생
if(cookies!=null){
for(Cookie c: cookies){
out.println(c.getName());
out.println("<br>");
out.println(c.getValue());
out.println("<br>");
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>쿠키 사용하기</h3>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//쿠키삭제 - 쿠키는 삭제가 없어서 동일한 이름의 쿠키를 0초로 만들어서 삭제
Cookie idCookie = new Cookie("user_id", "kkk123");//이름 , 값
idCookie.setMaxAge(0);//시간
response.addCookie(idCookie);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
쿠키는 삭제가 없어서 따로 동일한 이름의 쿠키를 0초로 만든다.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
이 페이지 처음 진입하면 idCheck쿠키를 찾아서 값을 얻고
아이디 태그 안에 미리 값을 넣어주는 코드를 작성
input태그에 value속성을 쓰면 됨
*/
String id = "";
Cookie[] arr = request.getCookies();
if(arr!=null){
for(Cookie c :arr){
if(c.getName().equals("idCheck")){
id = c.getValue();
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>쿠키 로그인 연습</h2>
<form action="cookie_ex02_ok.jsp" method="post">
아이디:<input type="text" name="id" size ="10" value=<%=id %>>
비밀번호:<input type="text" name="pw" size ="10">
<input type="submit" value="로그인">
<input type="checkbox" name="idCheck" value="y">아이디기억하기
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//
request.setCharacterEncoding("utf-8");
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String idCheck = request.getParameter("idCheck");
//idCheck쿠키
//사용자가 체크박스를 체크 했다면 idCheck를 생성 시간은 30초
if(idCheck!=null){
Cookie cook = new Cookie("idCheck",id);
cook.setMaxAge(10);
response.addCookie(cook);
}
//로그인 성공이라 가정
if(id.equals("aaa123") && pw.equals("1234")){
//로그인 성공시 id쿠키 생성
Cookie cookie = new Cookie("user_id", id);
cookie.setMaxAge(1800);//30분
response.addCookie(cookie);
response.sendRedirect("cookie_ex02_welcome.jsp");//성공페이지
}else{
response.sendRedirect("cookie_ex02.jsp");//로그인 화면
}
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//user_id쿠키를 찾는 작업
Cookie[] arr = request.getCookies();
String id = "";
if(arr!=null){
for(Cookie c :arr){
if(c.getName().equals("user_id")){
id = c.getValue();
}
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
come on.(<%=id %>)
</body>
</html>
*세션
- 세션도 쿠키와 마찬가지로 서버와의 관계를 유지하기 위한 수단이다
- 단, 쿠키와 달리 클라이언트의 특정 위치에 저장되는 것이 아니라, 서버상에 객체형태로 존재
- 서버당 하나의 세션 객체를 가질 수 있다 (브라우저 별 서로 다른 세션 사용)
- 세션 객체는 브라우저 창을 종료하면 삭제됨
- 따라서 세션은 서버에서만 접근이 가능하여 보안이 좋고, 저장할 수 있는 데이터에 한계가 없다
- 세션은 클라이언트의 요청이 발생하면 자동생성되어 고유한 ID값을 클라이언트에 넘겨주며 이것은 쿠키에
저장된다.
- JSP에서는 session이라는 내장 객체를 지원하여 세션의 속성을 설정할 수 있다.
*세션객체 관련 메서드
-setAttribute() : 세션에 데이터를 저장할 때
-getAttribute() : 세션에 저장돼있는 데이터를 얻을 때
-removeAttribute() : 특정 세션를 삭제할 때
-invalidate() : 모든 세션을 다 삭제할 때
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
세션은 서버와 정보를 유지하기 위해 사용하는 내장객체
setAttribute("이름", 값)으로 저장
*/
session.setAttribute("user_id", "ccc123");
session.setAttribute("user_name", "이순신");
//시간설정
session.setMaxInactiveInterval(3600);//1시간 - 기본값 30분
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="session_ex01_ok.jsp">세션확인하기</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
세션에 저장된 값은 브라우저가 종료되기 전까지, 또는 기본 30분 유지되고
어느페이지에서나 사용할 수 있음
getAttribute("이름")을 사용
*/
String user_id = (String)session.getAttribute("user_id");
String user_name = (String)session.getAttribute("user_name");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
세션값:<%=user_id %><br>
세션값:<%=user_name %><br>
<a href="session_ex01_remove.jsp">세션삭제</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//세션삭제
session.removeAttribute("user_id");
//세션얻기
String user_id = (String)session.getAttribute("user_id");
String user_name = (String)session.getAttribute("user_name");
//세션전부삭제
session.invalidate();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>리무브된 결과</h3>
세션값:<%=user_id %><br>
세션값:<%=user_name %><br>
</body>
</html>
<%@ 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>
<h2>세션 로그인 연습</h2>
<form action="session_login_ok.jsp" method="post">
아이디:<input type="text" name="id"><br>
비밀번호:<input type="password" name="pw"><br>
닉네임:<input type="text" name="name"><br>
<input type="submit" value="로그인">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
/*
1. 아이디, 비밀번호, nick을 받습니다.
2. 아이디 비밀번호가 동일하면 로그인 성공이라고 간주하고 (user_id, id)의 세션생성
(user_nick, 닉네임)을 세션을 생성
session_welcome로 이동해서 화면에 "id님 환영합니다"를 출력합니다.
틀린경우는 로그인페이지로 리다이렉트 처리해주세요.
session_welcome페이지에서는 a태그를 이용해서 session_logout을 만들고,
세션을 무효화한 이후에 로그인 페이지로 리다이렉트 시키면 됩니다
*/
request.setCharacterEncoding("utf-8");//한글처리
String id = request.getParameter("id");
String pw = request.getParameter("pw");
String name = request.getParameter("name");
if(id.equals("1234") && pw.equals("1234")){
session.setAttribute("user_id",id);
session.setAttribute("user_nick", name);
response.sendRedirect("session_welcome.jsp");
}else{
response.sendRedirect("session_login.jsp");
}
%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String user_id = (String)session.getAttribute("user_id");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=user_id%>님 환영합니다<br>
<a href="session_logout.jsp">로그아웃</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
session.invalidate();
response.sendRedirect("session_login.jsp");
%>