HTML_JS(Sol)/JSP(sol)

210512_5~8(JSP내부객체 request, response, session, out)

너굴셉 2021. 5. 12. 16:06

JSP내부객체 9가지

1) request : 요청정보를 담고 있는 객체 *****

2) response : 응답정보를 담고있는 객체 ****

3) session : 세션변수를 호출, 생성, 소멸 ******

4) out : 출력관련 정보, 버퍼포함 ***

5) config : 환경정보

6) application : 웹어플 관련 정보 ***

7) pageContext : 페이지 내용물 객체 ***

8) page : 웹페이지 자체 

9) exception : 예외정보 객체 ***

 

각 객체당 메서드가 있다.

request

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Request Example1.html</title>
</head>
<body>
	<h1>Request Example1</h1>
	<Form Method=Post Action="RequestExample1.jsp">
		성명:<input type="text" name="name"><br> 
		학번:<input type="text" name="studentNum"><br> 
		성별: 남자<input type="radio" name="sex" value="man" checked> 
		여자<input type="radio" name="sex" value="woman"><br> 
		전공:<select name="major">
			<option selected value="국문학과">국문학과</option>
			<option value="영문학과">영문학과</option>
			<option value="수학과">수학과</option>
			<option value="정치학과">정치학과</option>
			<option value="체육학과">체육학과</option>
		</select><br> <input type="submit" value="보내기">

	</Form>
</body>
</html>
<h1>Request Example1</h1>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
	pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<%
	request.setCharacterEncoding("euc-kr");
%>
<%
String name = request.getParameter("name");
String studentNum = request.getParameter("studentNum");
String sex = request.getParameter("sex");
String major = request.getParameter("major");

if (sex.equals("man")) {
	sex = "남자";
} else {
	sex = "여자";
}
%>

<title>Request Example1.jsp</title>
<body>
	성명:
	<%=name%><p>
		학번:
		<%=studentNum%>
	<p>
		성별:
		<%=sex%>
	<p>
		학과:
		<%=major%>
	<p>
</body>

 

URL : http://도메인:포트/웹루트

URI :    X         X :  X /웹루트

URL ⊂URI (포함관계) URI안에 URL이 있다.

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<%
String protocol = request.getProtocol();
// protocol--->http 
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String remoteAddr = request.getRemoteAddr();
// 클라이언트주소
String remoteHost = request.getRemoteHost();
//host(서버)
String method = request.getMethod();
//post or get
StringBuffer requestURL = request.getRequestURL();
//URL : http://도메인:포트/웹루트
String requestURI = request.getRequestURI();
//URI :    X         X :  X /웹루트
String useBrowser = request.getHeader("User-Agent");
// 사용자를 대리하는것
String fileType = request.getHeader("Accept");
//인식할수있는 문서가 무엇이냐
%>
<html>
<head>
<meta charset="EUC-KR">
<title>RequestExample2.jsp</title>
</head>
<body>
<h1>Request Example2</h1>
프로토콜 :<%=protocol %><p>
서버의 이름:<%=serverName%><p>
서버의 포트 번호: <%=serverPort %><p>
사용자 컴퓨터의 주소 : <%=remoteAddr%><p>
사용자 컴퓨터의 이름 : <%=remoteHost%><p>
사용 method : <%=method%><p>
요청 경로(URL) :<%=requestURL%><p>
요청경로(URI) : <%=requestURI%><p>
현재 사용하는 브라우저 : <%=useBrowser%><p>
브라우저가 지원하는 file의 type : <%=fileType%><p>

</body>
</html>


이동

response

response.sendRedirect("경/파")

 

기존 : 브라우저 ---------A요청-------->A.jsp

                    <--------A응답---------

 

포워드 된경우 : 브라우저 -------A요청------->A.jsp --forward--> B.jsp

                                 <--------------------B응답--------------

                    특징 : 브라우저주소는 A를 가리킨다. 하지만 브라우저화면은 B를 출력한다.

                               브라우저입장에서는 B페이지의 존재를 알수가없다.

                    결론 : A와 B사이는 include 처럼 request영역을 공유한다. ex) A입력처리 -영향미침->B 입력결과

 

리다이렉트 : 브라우저 -------A요청------->A.jsp --redirect--> B.jsp

                            <---------B로이동할것

                             ------------------B요청----------------->

                             <--------------B응답---------------------

                   특징 : 브라우저 주소 : A->B를 가르킨다.

                            브라우저 화면 :     B를 출력한다.

                   결론 : A와 B는 관계가 없다.

                           A는 입력처리 B는 목록 출력처리

캐쉬저장

 respense.setHeader(키,값);

Pragma , no-cache

Cache-Control , no-cache <===요즘은 거의 HTML 1.1

서버로부터 받은 데이타를  브라우저 캐쉬에 저장하지 않도록 설정하는 것.

따라서 이페이지는 항상 서버로부터 새롭게 페이지를 다운로드한다.

 예) 뒤로 돌아갈수 없는 페이지 만들때

<h1>Response Example1</h1>
<%
response.sendRedirect("ResponseExample1_1.jsp");
// ResponseExample1_1.jsp 로 이동하라.
%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<%
response.setHeader("Pragma","no-cache");
// 요청결과를 브라우저 캐쉬에 저장하지말라는것 (HTTP/1.0)
// 항상 새로운페이지를 받을때 사용하는것.
if(request.getProtocol().equals("HTTP/1.1")){
	//똑같은 명령 버전차이
response.setHeader("Cache-Control", "no-cache");
}
%>
<html>
<head>
<meta charset="EUC-KR">
<title>Response Exmaple1</title>
</head>
<body>
<h1>Response Exmaple1</h1>
http://localhost:8080/myapp/ch06/ResponseExample1.jsp가<p>
http://localhost:8080/myapp/ch06/ResponseExmaple1_1.jsp로 변경이 되었습니다.
</body>
</html>

 

Out

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" buffer="5kb"%>
<!DOCTYPE html>

<%
int totalBuffer = out.getBufferSize();
int remainBuffer = out.getRemaining();
int useBuffer = totalBuffer - remainBuffer;
%>
<h1>Out Example1</h1>
<b>현재 페이지의 Buffer 상태</b><p>
출력 Buffer의 전체 크기 : <%=totalBuffer %><p>
남은 Buffer의 크기 : <%=remainBuffer %><p>
현재 Buffer의 사용량 : <%=useBuffer %><p>

 

반드시 습득할것

전송--->수신


session 세션

세션이란? 투컴퓨터 사이에 통신이 시도,유지 되는 과정 - 네트워크에서 의미

웹에서 세션 . 세션의 의미 -------- 로그인 되어있나? ---> 어떻게 판단하나

                                             1) 식별 여부       ---> sessionID

                                             2) 권한 여부       ---> session변수

sessionID : 최초로 특정 서버에 접속하는 순간 서버는 클라이언트를 구별하기 위해서

               특정한 값(30여자정도 문자열)을 부여하는데 이것을 세션id라고 한다.

session변수 : 연동을 통해서 id,pw 확인된 유저는 session변수를 생성할 수 있도록 해준다.

                   그 변수를 체크해서 권한을 확인하는 것임.

                 유지시간을 설정할 수 있음, 디폴트는 30분이다.

                  많이 발생시키면, 서버메모리 소비하게 된다. 주의한다.

                  내가 저장한 변수는 나만 꺼낼수있다.

                   저장 : session.setAttriubute(키,값);

                   꺼냄 : session.getAttribute(키);

                   시간설정 : session.setMaxInactiveInterval(초); cf.나중에 쿠키랑 같이 이야기

 

jsp페이지에서 session 설정 하지 않으면 디폴트 true가 된다.

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Session Example1.html</title>
</head>
<body>
<h1>Session Example1</h1>

<form method=post action="SessionExample1.jsp">
아이디 : <input type = "text" name="id"><p>
비밀번호 : <input type="password" name="password"><p>
<input type="submit" value ="로그인">
</form>

</body>
</html>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR" session ="true"%>
<!DOCTYPE html>
<%
request.setCharacterEncoding("euc-kr");
%>
<%
String id = request.getParameter("id");
String password = request.getParameter("password");

session.setAttribute("idKey", id);
//세션변수.idKey라는 변수에 id를 담는다
session.setMaxInactiveInterval(60*5);
//세션의 유효시간은(60*5초동안)유지되도록 설정 default에서는 30분이다.
%>
<h1>Session Example1</h1>
<form Method="post" Action="SessionExample1_1.jsp">
1.가장 좋아하는 계절은?<br>
<input type="radio" name="season" value="봄">봄
<input type="radio" name="season" value="여름">여름
<input type="radio" name="season" value="가을">가을
<input type="radio" name="season" value="겨울">겨울<br>

2.가장 좋아하는 과일은?<br>
<input type="radio" name="fruit" value="watermelon">수박
<input type="radio" name="fruit" value="melon">멜론
<input type="radio" name="fruit" value="apple">사과
<input type="radio" name="fruit" value="orange">오렌지
<input type="submit" value="결과보기">
</form>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html>
<%
request.setCharacterEncoding("euc-kr");
%>
<h1>Session Example1</h1>
<%
String season = request.getParameter("season");
String fruit = request.getParameter("fruit");
String id = (String)session.getAttribute("idKey");
//세션영역에서 idKey값을 꺼내온다
String sessionId = session.getId();
//세션변수를 구별하는 식별자 값 .서버가 클라이언트를 구별할때 쓰는 값
int intervalTime = session.getMaxInactiveInterval();

if (id!=null){ //'로그인을했다면'
%>
<b><%=id %></b>님이 좋아하시는 계절과 과일은<p>
<b><%=season %></b>과 <b><%=fruit %></b>입니다.<p>
세션 ID : <%=sessionId%><p>
세션 유지 시간 : <%=intervalTime%>초<p>
<%
session.invalidate();
//세션제거.로그오프.id값을 날려버리는것 //새로고침을 해볼것.
}else{
out.print("세션의 시간이 경과를 하였거나 다른 이유로 연결을 할 수가 없습니다.");
}
%>

 

새로고침을 했을때 세션이 날아간다  session.invalidate();


범위 

=============page

페이지 변수

=================request

요청과 응답의 관련 페이지

 include, forward는 request를 공유한다.

========================session : 개별변수

어디서나 저장, 어디서나 호출.

그런데 내가 저장한것은 나만꺼낸다(호출).  ex) 나만증가시킬수 있는 카운터

=============================application : 공용변수

어디서나 저장, 어디서나 호출가능.

내가 저장한것을 다른유저가 꺼낼(호출)수있다. ex) 누구나 증가시킬수 있는 카운터