Recent Posts
Recent Comments
Link
06-30 12:53
Today
Total
관리 메뉴

삶 가운데 남긴 기록 AACII.TISTORY.COM

JSP 내장 객체 본문

DEV&OPS/Java

JSP 내장 객체

ALEPH.GEM 2022. 6. 21. 15:48

내장 객체

서블릿에서는 변수, 메소드, 객체를 선언하고 초기화 한 후에 사용하지만 jsp에서는 내장되어 있는 객체들이 있어서 선언 및 초기화를 하지 않고 바로 사용할 수 있는 내장 객체들이 있습니다.

내장 객체들과 같은 이름으로 객체를 선언하려고 하면 오류가 발생합니다.

  • request : HttpServletRequest 객체
  • response : HttpServletResponse 객체
  • session : HttpSession 객체
  • application : ServletContext 객체
  • config : ServletConfig 객체
  • out : JspWriter 객체(출력 처리)
  • pageContext : PageContext 객체(jsp 페이지 처리 객체)

 

request, response 객체

logInOut.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>
<%
	String msg = (String)request.getAttribute("error");
	if(msg == null) msg = "";
%>

<%=msg %>

	<form action="example10.jsp" method="post">
		ID:<input type="text" name="id"><br>
		비밀번호:<input type="password" name="pwd"><br>
		<input type="submit" value="로그인">
	</form>
</body>
</html>

example10.jsp로 id와 pwd를 제출하는 페이지 입니다.

example10.jsp에서 입력값이 없으면 다시 logInOut.jsp로 다시 포워드(이동) 할 때 에러 메시지를 받기위해 request.getAttribute()를 사용했습니다.

 

example10.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>
<%
	//내장객체 request 를 이용해서 parameter 값을 획득
	String id = request.getParameter("id");
	String pwd = request.getParameter("pwd");

	//id, pwd가 입력을 안했을 경우는 원래 페이지로 forwad 시킴
	if(id.isEmpty() || pwd.isEmpty()){
		request.setAttribute("error","ID또는 비밀번호를 입력하세요.");
		RequestDispatcher rd = request.getRequestDispatcher("logInOut.jsp");
		rd.forward(request, response);
		return;
	}
%>

<%=id %> / <%=pwd %>
</body>
</html>

내장 객체은 request객체에 attribute를 추가하기 위해 request.setAttribute()메소드를 사용했습니다.

id나 pwd 입력값이 없는 경우 RequestDispatcher를 이용해 다시 logInOut.jsp로 포워딩합니다.

 

session 객체

session은 클라이언트 단위로 정보를 유지합니다.

그래서 대표적으로 로그인 정보를 유지하는데 세션 객체를 이용합니다.

위에서 작성했던 example10.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>
<%
	//내장객체 request 를 이용해서 parameter 값을 획득
	String id = request.getParameter("id");
	String pwd = request.getParameter("pwd");

	//id, pwd가 입력을 안했을 경우는 원래 페이지로 forwad 시킴
	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 %>
</body>
</html>

session.isNew() 는 새 세션이 생성되면 true를 리턴하고 기존 세션 객체를 리턴하면 false를 리턴합니다.

session.setAttribute()로 세션객체에 id값을 등록해서 로그인 상태인지 아닌지 알 수 있도록 합니다.

 

이제 위에서 작업했던 logInOut.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>
<%
	if(session.isNew() || session.getAttribute("id") == null){	

	String msg = (String)request.getAttribute("error");
	if(msg == null) msg = "";
%>

<%=msg %>

	<form action="example10.jsp" method="post">
		ID:<input type="text" name="id"><br>
		비밀번호:<input type="password" name="pwd"><br>
		<input type="submit" value="로그인">
	</form>
<%
	}else{
%>	
	<a href="example10.jsp">로그아웃</a>
<%
	}
%>
</body>
</html>

로그아웃 문자열에 하이퍼링크<a> 를 추가하여 example10.jsp를 실행하도록 링크를 등록했습니다.

이제 example10.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>
<%
	if(request.getMethod().equalsIgnoreCase("POST")){	

		//내장객체 request 를 이용해서 parameter 값을 획득
		String id = request.getParameter("id");
		String pwd = request.getParameter("pwd");
	
		//id, pwd가 입력을 안했을 경우는 원래 페이지로 forwad 시킴
		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(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>

위 예제에서 앵커 태그<a> 으로 이동한 페이지는 doGet() 메소드가 처리하므로 POST인지 GET인지 여부에 따라 POST는 로그인 처리 GET은 로그아웃 처리를 했습니다.

 

out 객체

out 내장 객체는 서블릿에서의 PrintWriter와 비슷합니다.

example11.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>
<%
	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>

 

application 객체

application 내장 객체는 ServletContext타입입니다. 

그래서 웹어플리케이션이 시작될 때 시작되어 상태 정보를 유지합니다.

example12.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>
서버명:<%=application.getServerInfo() %><br>
서블릿 버전:<%=application.getMajorVersion() %>.<%=application.getMinorVersion() %><br>
<h3>/jsp </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>

 

pageContext 객체

pageContext는 서블릿에는 없지만 jsp 페이지 하나당 각각 생성되는 객체입니다.

 

test.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>
<h3> hello test.jsp</h3>
</body>
</html>

 

example13.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>
<%! 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>

 

 

 

 

 

 

 

 

728x90

'DEV&OPS > Java' 카테고리의 다른 글

JDBC 프로그래밍  (0) 2022.06.30
표준 액션 태그 jsp java beans  (0) 2022.06.22
JSP  (0) 2022.06.20
web.xml 서블릿 오류 처리  (0) 2022.06.20
리스너 Listener  (0) 2022.06.20