-
내장 객체란?
프로그램에서 변수를 사용하려면 변수를 선언하고 초기화 작업이 선행되어야함.1. 변수 선언 -> PrintWriter out;2. 변수 초기화 -> out = res.getWriter();3. 변수 사용 -> out.print("Hello");JSP파일에서 선언 및 초기화를 하지 않고서 바로 사용할 수있는 변수들이 있다. 이렇게 사용할 수 있는 이유를 알기 위해JSP 파일의 동작 원리를 다시 생각한다.
JSP 파일을 작성할때 HTML 태그와 JSP 태그를 사용하여 작성한 다음 확장자를 jsp로 저장하면 개발자가 할 일은 끝난다.
이런 JSP파일이 실행 될 때는 완벽한 자바 소스로 변환되고 , 이자바 소스가 컴파일 되어 실행 파일이 실행된다.
이 과정 중 JSP파일이 자바 소스로 변환 될때 _JSPService() 메소드가 반드시 삽입되며 , JSP가 실행 될 때마다 자동으로 호출된다.
_jspService() 메소드 안에 자동으로 생성되는 코드가 있다.
_jspService메서드 부분
public
void
_jspService(HttpServletRequest request, HttpServletResponse response)
throws
java.io.IOException, ServletException {
JspFactory _jspxFactory =
null
;
PageContext pageContext =
null
;
HttpSession session =
null
;
ServletContext application =
null
;
ServletConfig config =
null
;
JspWriter out =
null
;
Object page =
this
;
String _value =
null
;
try
{
if
(_jspx_inited ==
false
) {
synchronized
(
this
) {
if
(_jspx_inited ==
false
) {
_jspx_init();
_jspx_inited =
true
;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType(
"text/html;charset=ISO-8859-1"
);
pageContext = _jspxFactory.getPageContext(this, request, response,
""
,true,
8192
,
true
);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
출처: https://unabated.tistory.com/entry/JSP-내부-jspService-메서드의구조 [랄라라]모든 JSP파일이 자바 소스로 변환될때 공통으로 삽입되는 코드이다.
public
void
_jspService(HttpServletRequest request, HttpServletResponse response)
전달되는 객체는 HttpServletRequest 와 HttpServletResponse
JspFactory _jspxFactory =
null
;
PageContext pageContext =
null
;
HttpSession session =
null
;
ServletContext application =
null
;
ServletConfig config =
null
;
JspWriter out =
null
;
Object page =
this
;
String _value =
null
;
변수를 선언 하고 초기화하는 부분
out = pageContext.getOut();
out이라는 변수를 선언하고 초기화
이렇게 메소드 내에 자동으로 선언 및 초기화 되는 변수들은 '내장 객체' 라고 한다.
내장 객체는 JSP페이지에는 별도의 선언 및 초기화 작업 없이 바로 사용할 수있다.
JSP 객체를 정리한 표
변수이름
타입
설명
request
javax.servlet.http.HttpServletReqeust
요청정보 처리 객체
response
javax.servlet.http.HttpServletResponse
응답정보 처리 객체
session
javax.servlet.http.HttpSession
상태정보 유지 객체
application
javax.servlet.http.ServleetContext
상태정보 유지 객체
config
javax.servlet.ServletConfig
서블릿 정보 추출 객체
out
javax.servlet.jsp.JspWriter
출력 처리 객체
pageContext
javax.servlet.jsp.PageContext
JSP 페이지 처리 객체
request , response
요청 정보와 응답정보를 활용하는 예제id, pwd 질의 문자열로 보냄12345678910111213141516171819202122<%@ 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><%String msg =(String) request.getAttribute("error");if(msg == null) msg ="";%><%= msg %><form action="example3.jsp" method="post">ID: <input type="text" name="id"><br>비밀번호 : <input type="password" name="pwd"><br><input type="submit" value="로그인"></form></body></html>cs 정확히 입력하면 출력하고
입력을 안하고 요청하면
다시 forward 방식으로 돌려보냄
이때 set attribute로 error내용에 대한 문자열을 보냄
123456789101112131415161718192021222324<%@ 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><%String id = request.getParameter("id");String pwd = request.getParameter("pwd");if(id.isEmpty() || pwd.isEmpty()){request.setAttribute("error", "ID 또는 비밀번호를 입력해 주세요");RequestDispatcher rd = request.getRequestDispatcher("logInOut.jsp");rd.forward(request, response);return;}%><%= id %>/<%= pwd %></body></html>cs session
HttpSession.의 내장 객체로서 클라이언트 마다 하나씩 생성되면, 클라이언트단위로 정보를 유지하고자 할때 사용한다.1234567891011121314151617181920212223242526<%@ 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><%if(session.isNew() || session.getAttribute("id")==null){ %><%String msg =(String) request.getAttribute("error");if(msg == null) msg ="";%><%= msg %><form action="example3.jsp" method="post">ID: <input type="text" name="id"><br>비밀번호 : <input type="password" name="pwd"><br><input type="submit" value="로그인"></form><%}else { %><a href="example3.jsp"></a><%} %></body></html>cs 세션의 유무를 판단하고 로그인 상태라면 로그아웃 링크만 보이게 만듬123456789101112131415161718192021222324252627282930313233343536373839404142434445464748<%@ 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><%if (request.getMethod().equals("POST")) {%><%String id = request.getParameter("id");String pwd = request.getParameter("pwd");//유효성 체크if (id.isEmpty() || pwd.isEmpty()) {request.setAttribute("error", "ID 또는 비밀번호를 입력해 주세요");RequestDispatcher rd = request.getRequestDispatcher("logInOut.jsp");rd.forward(request, response);return;}//로그인 처리if (session.isNew() || session.getAttribute("id") == null) {session.setAttribute("id", id);out.print("로그인 작업이 완료되었습니다.");} else {out.print("이미 로그인 상태입니다.");}%><%=id%>/<%=pwd%><%} else if (request.getMethod().equals("GET")) {if(session != null && session.getAttribute("id")!=null){session.invalidate();out.print("로그아웃 작업이 완료 되었습니다.");}else{out.print("현재 로그인 상태가 아닙니다.");}}%><%RequestDispatcher rd = request.getRequestDispatcher("logInOut.jsp");rd.forward(request, response);%></body></html>cs 로그 아웃 버튼은 GET방식이므로 requst 객체에서 보내온 방식을 판단한뒤
분기를 만들어주고
다시 forward 방식으로 보낸다.
out
out 의 내장객체는 JspWriter 타입이다.웹 브라우저로 출력하는 기능을 하며 서블릿 구현시 사용하는 java.io.PrintWriter 객체와 비슷하다.out 내장 객체가 가지고 있는 메소드는 크게 두가지 이다.버퍼 관련 메소드와출력관련 메소드1234567891011121314151617181920212223242526272829303132<%@ 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><%int total = out.getBufferSize();out.print("첫번째 텍스트입니다.");out.clearBuffer();out.print("출력버퍼의 크기 : "+total);out.print("<br>사용되지 않은 버퍼의 크기 : "+ out.getRemaining());out.flush();out.print("<br>flush 후 버퍼 크기 : "+out.getRemaining());%><hr><h3>out.print() 메소드</h3><%out.print(100);out.print(true);out.print(3.14);out.print("TEST");out.print('가');out.print(new java.io.File("\\"));out.print("버퍼의 크기 : "+out.getRemaining());%></body></html>cs 출력버퍼의 크기 : 8192
사용되지 않은 버퍼의 크기 : 8177
flush 후 버퍼 크기 : 8192out.print() 메소드
100true3.14TEST가\버퍼의 크기 : 8114
소스 설명
int total = out.getBufferSize();
출력스트림을 외부로 보낼때 버퍼를 이용한다. 기본버퍼의 크기를 추출하는 메소드
out.print("첫번째 텍스트입니다.");
out.clearBuffer();
out.clearBuffer();는 메소드는 버퍼에 있는 내용을 삭제하는 메소드
out.print("첫번째 텍스트입니다.");에서 문자열을 출력했지만
실제 전송이 되지않고 버퍼에 있다.
버퍼에 있는 상태에서
삭제가 진행되었으므로 실제 전송이 이루어지지않고 삭제
out.flush();
버퍼에 있는 내용을 강제로 전송
버퍼가 꽉 차있는지 상관없이 버퍼의 내용을 전송한다.
out.print("<br>flush 후 버퍼 크기 : "+out.getRemaining());
out.flush를 수행한후 out.getRemaining()); 메소드를 이용하여
버퍼에 남은 크기를 구하면 버퍼의 전체크기와 같은 값이 반환된다.
반환형
이름
기능
abstract void
clear()
버퍼의 내용을 지웁니다. 버퍼의 모든 내용이 클라이언트에 전송이 완료된 후 실행되면 IOEception 이 발생한다.
clearBuffer()
버퍼의 내용을 지운다. 버퍼의 모든 내용이 클라이언트에 전송이 완료된후 실행되면 IOExecption이 발생하지 않는다.
close()
출력스트림을 해제한다.
flush()
버퍼의 내용을 강제로 전송한다.
int
getBufferSize()
버퍼의 크기를 추출한다.
abstract int
getRemaining()
버퍼의 남아 있는 크기를 추출한다.
boolean
isAutoFlush()
버퍼의 크기만큼 내용이 채워졌을 때 자동 전송 여부를 확인한다.
application
application 내장객체는 ServletContext 타입이다.웹애플리케이션마다 하나씩 , 서비스가 시작될때 생성되는 객체로서 , 서버에 대한 정보 추출과 웹 애플리케이션 단위로 상태정보를 유지하기 위해 사용한다.application 내장 객체를 사용해서 ServletContext 객체가 가지고 있는 메소드들을 사용해 보자1234567891011121314151617181920212223<%@ 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>서버명 : <%= application.getServerInfo() %>서블릿 버전 : <%= application.getMajorVersion() %><h3>/edu 리스트</h3><%java.util.Set<String> list = application.getResourcePaths("/");if(list != null){Object[] obj = list.toArray();for(int i = 0 ; i<obj.length; i++){out.print(obj[i] +"<br>");}}%></body></html>cs 결과
서버명 : Apache Tomcat/8.5.34 서블릿 버전 : 3
/edu 리스트
/ex2.jsp
/example12.jsp
/example3.jsp
/logInOut.jsp
/name.html
/input.html
/META-INF/
/example11.jsp
/index.jsp
/loginOut.html
/member.html
/WEB-INF/
/bookInput.html
/site.htmlapplication.getServerInfo() :현재 사용중인 서버정보 추출
application.getMajorVersion() : 서블릿 버전 추출
java.util.Set<String> list = application.getResourcePaths("/");
= 인자로 지정한 디렉터리의 목록을 반환한다.
반환된 값이 있으면 실행되는 부분 배열로 바꿔서 하나씩 꺼내는 루프
if(list != null){
Object[] obj = list.toArray();
for(int i = 0 ; i<obj.length; i++){
out.print(obj[i] +"<br>");
}
}
pageContext
pageContext 내장 객체는 PageContext 타입이다.PageContext는 서블릿을 학습할때 보지 못했던 객체이다.PageContext는 JSP페이지당 하나씩 자동으로 생성되는 객체이기때문이다.pageContext 객체가 가지고 있는 메소드는 다음과 같다.
반환형
메소드명&인자
기능
void
forward(String relative UrlPath)
인자값으로 지정된 페이지로 이동
Exception
getException( )
현재 발생된 Exception 객체를 반환한다.
Object
getPage()
현재 JSP문서정보 객체를 반환한다.
ServletRequest
getRequest( )
현재 JSP문서의 HttpServletRequest를 반환
ServletResponse
getResponse()
현재 JSP문서의 HttpServletResponse를 반환한다.
ServletConfig
getServletConfig()
현재 JSP문서의 ServletConfig 객체를 반환한다.
ServletContext
getServletContext()
현재 JSP문서의 ServletContext 객체를 반환한다.
HttpSession
getSession()
현재 JSP문서의 HttpSession 객체를 반환한다. void
include(String relativeUrlPath)
인자값으로 지정된 페이지를 현재 JSP문서에 포함한다.
12345678910111213141516171819202122232425262728293031<%@ 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><%!public void work(String p, PageContext pc){try{JspWriter out = pc.getOut();if(p.equals("include")){out.print("---include 전 --<br>");pc.include("test.jsp");out.print("--include 후 -- <br>");}else if (p.equals("forward")){pc.forward("test.jsp");}}catch(Exception e){System.out.println("오류 발생");}}%><%String p = request.getParameter("p");this.work(p, pageContext);%></body></html>cs JspWriter out = pc.getOut();
이부분을 보면 out은 내장객체인데 pageContext로 변수선언과 초기화를 이룬다
내장객체는 _jspService() 메소드 내에서만 사용할 수있는 지역변수인 것이다.
<%...%> 와 <%= ...%> 태그 에서만 사용할 수있다.
만일 다른 메소드에서 내장객체를 사용하려면 기본적으로 사용할 수 없고 ,PageContext내장 객체를 이용해야한다.
이것이 객체의 2번째기능 이다
'Servlet' 카테고리의 다른 글
표준 액션태그와 JSP 자바빈즈 (0) 2019.03.04 내장객체 요약 (0) 2019.03.04 JSP프로그래밍 정리 (0) 2019.03.03 JSP프로그래밍 (0) 2019.03.02 상태정보 유지 기술 (0) 2019.02.25