수업내용/Java

[2022.11.08.화] JSP 내장객체, JSP 요청객체

주니어주니 2022. 11. 8. 21:06

 

 

1. JSP 내장객체 

 

  • JSP 페이지가 자바로 변환될 때 _jspService메소드에서 사용가능한 객체
  • JSP는 웹 애플리케이션 개발에 필요한 객체를 미리 생성(획득)해서 적절한 변수에 저장하고, 스크립트릿에서 사용가능한 상태로 초기화시켜놓는다.

 

 

* 객체 생성, 참조변수 선언

 

* 참주변수에 객체 대입

 

 

* sample.jsp 는 톰캣에 의해 자동으로 sample_jsp.java로 변환 

 

* 스크립틀릿에서 입력한 소스는 객체 생성 아래에 위치하기 때문에, 스크립틀릿에서도 내장객체를 사용할 수 있음!

 

 

 

 

* JSP의 다양한 내장객체 

 

변수명 클래스명 설명
request HttpServletRequest 클라이언트가 보낸 요청메세지 정보를 저장한다.
response HttpServletResponse 클라이언트로 보낼 응답메세지 정보를 저장한다.
session HttpSession 세션정보를 저장한다.(로그인처리와 관련)
out JspWriter 응답컨텐츠를 클라이언트로 출력하는 스트림
application ServletContext 웹 애플리케이션을 나타내는 객체다..
config ServletConfig 서블릿의 초기화에 필요한 정보를 저장한다.
pageContext PageContext JSP 페이지에 대한 정보를 저장한다.
exception Throwable 에러정보를 저장한다.(isErrorPage="true")에서만 사용가능
page Object JSP 페이지를 구현한 자바객체가 저장된다.

 

 

 

 

 

JSP가 실행될 때 톰캣이 자동으로 내장객체를 생성해서 바로 사용할 수 있도록 변수에 이미 다 넣어놨어

Request, Response, Config, Context, PageContext (jspService 안에서 만드는 객체) 등등

 

웹 브라우저에서 요청 -> HTTP 요청메시지를 분석

-> 톰캣에서 자동으로 생성한 Request 객체에 요청메시지 정보를 저장 -> 이 객체가 request 변수에 저장

-> Response 객체에 응답 메시지를 제공 -> 웹 브라우저로 응답 

 

 

 

1-1. HttpServletRequest

 

  • request 변수에 저장된다.
  • 클라이언트가 서버로 보낸 요청 메세지를 저장하고 있다
  • 요청메세지정보를 획득할 수 있는 다양한 getXXX() 메소드를 제공한다.
  • 주요 메소드
<%@page import="java.util.Locale"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>HttpServletRequest 객체</h1>
	<p><%=request %></p>
	
	<%
		// HttpServletRequest의 주요 메소드
		
		
		// String getMethod()는 요청방식을 반환한다.
		String method = request.getMethod();
	
		// String getContextPath()는 웹 애플리케이션의 context path를 반환한다.
		String contextPath = request.getContextPath();
		
		// String getRequestURI()는 요청 URI를 반환한다.
		String requestURI = request.getRequestURI();
		
		// String getRemoteAddr()은 서버로 요청을 보낸 클라이언트의 ip 주소를 반환한다.
		String ipAddress = request.getRemoteAddr();
		
		// Locale getLocale()은 서버로 요청을 보낸 클라이언트의 로케일 정보(브라우저의 기본언어, 국가정보)를 반환한다. 
		Locale locale = request.getLocale();
		
		// String getHeader(String name)은 요청메시지의 요청 헤더정보(클라이언트에 관한 부가정보)를 반환한다. 
		String agent = request.getHeader("user-agent");
		String accept = request.getHeader("accept");
		String acceptEncoding = request.getHeader("accept-encoding");
		String acceptLanguage = request.getHeader("accept-language");
	%>
	
	<h3>요청객체가 가지고 있는 주요 정보</h3>
	<dl>
		<dt>요청방식</dt><dd><%=method %></dd>
		<dt>컨텍스트 패스</dt><dd><%=contextPath %></dd>
		<dt>요청 URI</dt><dd><%=requestURI %></dd>
		<dt>클라이언트의 ip 주소</dt><dd><%=ipAddress %></dd>
		<dt>클라이언트의 로케일정보</dt><dd><%=locale %></dd>
	</dl>
	
	<h3>요청메시지의 헤더정보</h3>
	<dl>
		<dt>클라이언트의 브라우저 정보</dt><dd><%=agent %></dd>
		<dt>클라이언트의 브라우저가 지원하는 콘텐츠 타입</dt><dd><%=accept %></dd>
		<dt>클라이언트의 브라우저가 지원하는 콘텐츠 압축 방식</dt><dd><%=acceptEncoding %></dd>
		<dt>클라이언트의 브라우저가 지원하는 언어</dt><dd><%=acceptLanguage %></dd>
	</dl>
</body>
</html>

 

 

 


 

 

 

※ 웹 브라우저에서 서버로 요청 파라미터값을 전달하는 3가지 방법

 

 

jsp만 호출하는게 아니라,  클라이언트가 요청한 것들 중 뭐를 클릭한 건지를 알아야 함 -> 뭔가 값을 더 전해줘야 함

-> 클라이언트가 보내는 정보 : 요청 파라미터 -> request.getParameter() 메소드 이용 

 

 

 

1) GET 방식 - 쿼리스트링 - 링크의 요청URL 뒤에 쿼리스트링 붙여놓기 

 

  • 쿼리스트링 : URL 뒤의 ? 뒤에 붙는 부가적인 정보
    • ? name = value
    • ? bookNo = 1001 

 

 

클라이언트의 요청 -> 쿼리스트링의 값(요청한 정보)이 Request객체 안의 요청파라미터 정보에 전부 알아서 들어가 있음

-> 그럼 이 요청파라미터 값을 어떻게 꺼낼 것이냐

-> _jspService 메소드를 실행하면 -> 이 Request 객체가 request 변수에 들어가잖아 

-> 이때 jsp에서 Request 객체의 getParameter() 메소드 실행 (지정된 이름의 요청파라미터 값을 반환한다)

 

request인터페이스를 구현해서 톰캣에서 구현한 객체가 있음

내가 실행하려는건 request인데 실제로 실행되는건 재정의된 메소드

전달해주면 request로 다시 클래스 형변환됨 

 

 

 

- sample-4.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>
	<h1>sample-5.jsp에 요청파라미터값 전달하기</h1>

	<h2>쿼리스트링으로 sample-5.jsp에 요청파라미터값 전달하기</h2>
	
	<h3>도서 목록</h3>
	<ul>
		<li><a href="sample-5.jsp?no=1001">이것이 자바다</a></li>
		<li><a href="sample-5.jsp?no=1002">자바의 정석</a></li>
		<li><a href="sample-5.jsp?no=1004">혼자서 공부하는 자바</a></li>
		<li><a href="sample-5.jsp?no=1005">혼자서 공부하는 파이썬</a></li>
		<li><a href="sample-5.jsp?no=1006">스프링 인 액션</a></li>
		<li><a href="sample-5.jsp?no=1008">스프링 클라우드로 개발하는 마이크로서비스</a></li>
	</ul>
</body>
</html>

 

- sample-5.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>
	<h1>sample-4.jsp에서 전달한 요청파라미터값 조회하기</h1>
	
	<h2>sample-4.jsp에서 쿼리스트링으로 전달한 요청파라미터값 조회하기</h2>
	
	<%
		String value = request.getParameter("no");
	%>
	<p>sample-4.jsp에서 sample-5.jsp로 전달한 값 : <%=value %></p>
	
</body>
</html>

 

 

 

* 링크 클릭 -> 쿼리스트링으로 요청파라미터 값 전달

  -> 쿼리스트링으로 전달한 요청파라미터를 reuest.getParameter("전달한 값") 메소드를 통해 조회

 

 

 

 


 

 

2) GET 방식 - 쿼리스트링 - 폼 입력값 제출하기

 

 

- form method="get" 으로 지정하고 submit 버튼을 누르면

  폼요소의 값이 URL뒤에 쿼리스트링 형태로 붙어서 서버로 전달된다.

- 입력요소의 name 속성에 설정한 값이 요청파라미터의 이름이 된다.

- 서버로 보내는 값이 2가지 이상일 때는 &로 구분한다.

(name1=value1&name2=value2&name3=value3 )  

 

 

 

 

- sample-4.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>
	<h1>sample-5.jsp에 요청파라미터값 전달하기</h1>
	
	<h2>입력폼을 이용해서 요청파라미터값 전달하기</h2>
	<form method="get" action="sample-5.jsp">
		<select name="opt">
			<option value="title"> 제목</option>
			<option value="author"> 저자</option>
			<option value="publisher"> 출판사</option>
			<option value="content"> 내용</option>
		</select>
		<input type="text" name="keyword" />
		<button type="submit">검색</button>
	</form>
</body>
</html>

 

 

- sample-5.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>
	<h1>sample-4.jsp에서 전달한 요청파라미터값 조회하기</h1>
	
	<h2>sample-4.jsp에서 쿼리스트링으로 전달한 요청파라미터값 조회하기</h2>
	
	<h2>입력폼으로 전달한 요청파라미터값 조회</h2>
	<%
		String searchOption = request.getParameter("opt");
		String searchKeyword = request.getParameter("keyword");
	%>
	<p>입력폼의 검색 옵션값: <%=searchOption %></p>
	<p>입력폼의 검색 키워드: <%=searchKeyword %></p>
	
</body>
</html>

 

 

 

 

 


 

 

3) POST 방식 - 입력폼

 

- form method="post" 으로 지정하고 submit 버튼을 누르면

  폼요소의 값이 URL뒤에 쿼리스트링 형태로 붙어서 서버로 전달된다.

 

 

- sample-4.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>
	<h1>sample-5.jsp에 요청파라미터값 전달하기</h1>

	<h2>POST 방식 - 입력폼을 이용해서 요청파라미터값 전달하기</h2>
	<form method="post" action="sample-5.jsp">
		<div>
			<label>이메일</label>
			<input type="email" name="email" />
		</div>
		<div>
			<label>비밀번호</label>
			<input type="password" name="password" />
		</div>
		<div>
			<label>비밀번호 확인</label>
			<input type="password" name="passwordConfirm" />
		</div>
		<div>
			<label>이름</label>
			<input type="text" name="name" />
		</div>
		<div>
			<label>전화번호</label>
			<input type="text" name="phone" />
		</div>
		<button type="submit">회원가입</button>
	</form>
</body>
</html>

 

- sample-5.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>
	<h1>sample-4.jsp에서 전달한 요청파라미터값 조회하기</h1>
	
	<h3>POST 방식 - 입력폼으로 전달한 요청파라미터값 조회</h3>
	<%
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String passwordConfirm = request.getParameter("passwordConfirm");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
	%>
	<p>이메일: <%=email %></p>
	<p>비밀번호: <%=password %></p>
	<p>비밀번호 확인: <%=passwordConfirm %></p>
	<p>이름: <%=name %></p>
	<p>전화번호: <%=phone %></p>
</body>
</html>

 

 

 

 


 

 

* GET 방식  POST방식

 

  •  GET 방식의 요청 (링크 클릭, 폼 입력값 제출) 
    • method = "get"이면 url 뒤를 봄

 

 

 

  • POST 방식의 요청 (폼입력값 제출)
    • method = "post"이면 요청메시지 바디부를 봄 (url에 안보임)

 

 


 

 

* 브라우저와 웹서버간의 요청과 응답

 

 

 

 

 

1. 브라우저에서 http://localhost/web-sample/sample-4.jsp 실행 요청

    -> 톰캣에서 Request, Response 객체, sample-4.jsp 객체 생성

    -> 요청메시지를 분석해서  Request 객체에 저장 

    -> Request, Response 객체를 jsp객체의 _jspService 메소드의 변수에 전달 

 

2.  jsp에서 작성했던 내용이 _jspService 메소드 내의 out.write() 메소드로 전달 

 

3.  out.write() 의 수행결과인 내용들이 전달 (응답으로 jsp를 전달하는 것이 아님) 

 

4. 브라우저에는 그 응답 콘텐츠인 html이 보이는 것

 

5. 검색을 누르면 sample-5.jsp?opt=title&keyword=자바 실행요청

     -> name="title", name="keyword"를 action="sample-5" 로 보내라 

     -> Request 요청객체로 요청파라미터 전달

 

6.  요청파라미터를 분석해서 그 요청객체가 메소드의 변수로 전달 

     -> request.getParameter 를 이용해서 이 요청객체에 들어있는 opt, keyword의 값을 뽑아내서 변수에 저장

     -> jsp에서 <p><%= %>에 적은 내용이 out.writer에 들어가고

 

7. 이 수행결과가 응답콘텐츠로 전달

 

8. 브라우저에 표출