본문 바로가기

서버/Servlet-JSP
JSP 내장 객체 - request, response, pageContext

// JSP(Servlet) 내장 객체, JSP Implicit Object

    - 개발자가 직접 생성하는 객체가 아니라, JSP(톰캣)가 미리 만들어서 제공하는 객체
    - 예약어 형태로 제공
    ~ request, response, session, pageContext  ★★★★4가지 매우 중요★★★★
    ~ out, application
    ~ config, page, exception 등
 
    
    ~ pageContext, request, session, application 
        - 객체 내부에 사용자(개발자) 데이터를 관리하는 저장소(컬렉션)를 가진다.★★★★
        - 내장객체.setAttribute(key, value)
        - 내장객체.getAttribute(key)  


1. request(입력 도구) : HttpServletRequest
        - 클라이언트 -> (행동) -> 서버
        a. 전송된 데이터 가져오기
        b. 전송된 데이터 인코딩
        c. 요청에 관련된 정보 가져오기

    ~ getParameter(name) : 사용자가 전달한 name과 일치하는 값 반환★
            - 모든 폼 컨트롤의 데이터를 받는다.
            - name이 1개일 때 사용한다.
            - 컨트롤은 존재하는데 값을 입력하지 않으면 "" 반환
            - 컨트롤이 존재하지 않으면 null 반환

    ~ getParameterNames() : 사용자가 전달한 키들을 Enumeration 객체로 반환★
            - name이 동일한 컨트롤이 2개 이상 전송될 때 사용한다.

    ~ getParameterValues(name) : 사용자가 전달한 name과 일치하는 값을 배열 형식으로 반환
    ~ getCookies() : 클라이언트에서 전달한 쿠키를 배열 형식으로 반환
    ~ getMethod() : 현재 요쳥 방식이 GET인지 POST인지 문자열로 반환
    ~ getSession() :현재 세션 객체 반환
    ~ getRemoteAddr() : 클라이언트의 IP 주소 반환
    ~ getProtocol() : 현재 서버의 프로토콜을 문자열로 반환
    ~ setCharacterEncoding() : 현재 JSP로 전달되는 내용을 지정한 문자셋으로 변환
    ~ getHeaderNames() : 현재 요청이 가지는 헤더의 이름들을 반환
    ~ getHeaders(name) : 현재 요청한 헤더에서 지정한 이름의 모든 값들 반환
    ~ getQueryString() :현재 요청에 포함된 쿼리 문자열 반환 ☆
    ~ getServerName() : 서버 도메인 반환
    ~ getServerPort() : 서버 포트번호 반환
    ~ getRequestURI() : 요청 URL 반환(자원 경로, 파일 이름)
    ~ getRequestURL() : 요청 URL 반환(자원 경로, 파일 이름 외에도 프로토콜, 도메인 등 포함)

    ~ getRemoteHost() : 클라이언트 주소 반환
    ~ getContextPath() : 컨텍스트의 경로 반환


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
response.setCharacterEncoding("UTF-8");
		
		String cnt_ = request.getParameter("cnt"); 
		
		int cnt = 5;
		if(cnt_ != null && !cnt_.equals("")) {
			cnt = Integer.parseInt(cnt_);
		}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jsp 연습 중입니다.</title>
</head>
<body>
	<%for(int i=0; i<cnt; i++) {%>
		안녕!<br>
	<%}%>		
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	int num = 0;
	String num_ = request.getParameter("n");
	if(num_ != null && !num_.equals(""))
		num = Integer.valueOf(num_);
%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>spaghetti</title>
</head>
<body>
	<% if(num%2 != 0) { %>
	홀수입니다.
	<% }
	else {
	%>
	짝수입니다.
	<% } %>
</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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<link rel="stylesheet" href="css/jquery-ui.css">
<style>

    #memberlist img{
        opacity: .3;
    }
   
    #memberlist img.ui-selected{
        opacity: 1;
    }

</style>
</head>
<body>

    <h1>폼 컨트롤 전송하기</h1>
    
    <form method="POST" action="ex08ok.jsp">
        
        <table>
            <tr>
                <th>텍스트 박스</th>
                <td><input type="text" name="txt1"></td>
            </tr>
            <tr>
                <th>암호 상자</th>
                <td><input type="password" name="pw1"></td>
            </tr>
            <tr>
                <th>다중 라인 텍스트 박스</th>
                <td><textarea name="txt2"></textarea></td>
            </tr>
            <tr>
                <th>체크 박스</th>
                <td><input type="checkbox" name="cb1"></td>
            </tr>
            <tr>
                <th>체크 박스</th>
                <td><input type="checkbox" name="cb2" value="yes"></td>
            </tr>
            <tr>
                <th>체크 박스들</th>
                <td>
                    <h3>당신의 취미?</h3>
                    <label><input type="checkbox" name="cb3" value="독서">독서</label>
                    <label><input type="checkbox" name="cb4" value="운동">운동</label>
                    <label><input type="checkbox" name="cb5" value="코딩">코딩</label>
                </td>
            </tr>
            <tr>
                <th>체크 박스들</th>
                <td>
                    <h3>당신의 취미?</h3>
                    <label><input type="checkbox" name="cb" value="독서">독서</label>
                    <label><input type="checkbox" name="cb" value="운동">운동</label>
                    <label><input type="checkbox" name="cb" value="코딩">코딩</label>
                </td>
            </tr>
            <tr>
                <th>라디오 버튼</th>
                <td>
                    <h3>성별?</h3>
                    <input type="radio" name="rb" value="m" checked> 남자
                    <input type="radio" name="rb" value="f"> 여자
                </td>
            </tr>
            <tr>
                <th>셀렉트 박스</th>
                <td>
                    <select name="sel1">
                        <option value="f1">사과</option>
                        <option value="f2">바나나</option>
                        <option value="f3">귤</option>
                    </select>
                </td>
            </tr>
            <tr>
                <th>셀렉트 박스</th>
                <td>
                    <select name="sel2" multiple>
                        <option value="f1">사과</option>
                        <option value="f2">바나나</option>
                        <option value="f3">귤</option>
                    </select>
                </td>
            </tr>
            <tr>
                <th>히든 태그</th>
                <td><input type="hidden" name="id" value="hong"></td>
            </tr>
            <tr>
                <th>색상</th>
                <td><input type="color" name="color1"></td>
            </tr>
            <tr>
                <th>날짜</th>
                <td><input type="date" name="date1"></td>
            </tr>
            <tr>
                <th>범위</th>
                <td><input type="range" name="range1"></td>
            </tr>
            <tr>
	            <th>사용자 정의 컨트롤</th>
	            <td>
	               <div id = "memberlist">
	                  <img src = "images/man_01.png" data-name = "홍길동">
	                  <img src = "images/man_02.png" data-name = "아무개">
	                  <img src = "images/man_03.png" data-name = "호호호">
	               </div>
	               <input type = "hidden" name = "member" id = "member">
	            </td>
            </tr> 
        </table>
        
        <div>
            <input type="submit" value="보내기">
        </div>
        
    </form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>

    $('#memberlist').selectable({
       
        selected: function(event, ui) {
            //alert(ui.selected);
            
            $('#member').val(ui.selected.dataset['name']);
        }
    
    });

</script>
</body>
</html>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.util.Arrays"%>.

<%
    
	//업무 코드
	
	request.setCharacterEncoding("UTF-8");

	//request.getParameter의 행동
	//1. 컨트롤은 존재하는데 값을 입력하지 않으면 "" 반환

	//텍스트 박스
	String txt1 = request.getParameter("txt1");
	
	//System.out.println(txt1 == null);      //false
	//System.out.println(txt1.equals(""));   //true
	
	
	//암호 상자
	String pw1 = request.getParameter("pw1");
	
	
	//다중라인 텍스트 박스
	String txt2 = request.getParameter("txt2");
	txt2 = txt2.replace("\r\n", "<br>");
	
	
	/* 
	   체크 박스
	   1. value O
	       a. 체크 O > value 전송
           b. 체크 X > null 전송

	   2. value X
	       a. 체크 O > "on" 전송
	       b. 체크 X > null 전송
  
    */
	
	
	
	String cb1 = request.getParameter("cb1");
	String cb2 = request.getParameter("cb2");
	
	String cb3 = request.getParameter("cb3");
	String cb4 = request.getParameter("cb4");
	String cb5 = request.getParameter("cb5");
	
	/* 
	String tmp = "";
	
	tmp += cb3 != null ? cb3 : "";
	tmp += ",";
	
	tmp += cb4 != null ? cb4 : "";
	tmp += ",";
	
	tmp += cb5 != null ? cb5 : "";
	tmp += ",";
	*/
	 
	String tmp = "";
	
	for (int i=3; i<=5; i++) {
	    tmp += request.getParameter("cb" + i) + ",";
	}
	
	//String cb = request.getParameter("cb"); // > 체크된 것들 중에서 첫 번째 값만 가져옴(name이 1개일 때 사용)
	
	//name이 동일한 컨트롤이 2개 이상 전송될 때 사용
	String[] cb = request.getParameterValues("cb");
	
	
	//라디오 버튼
	String rb = request.getParameter("rb");
	rb = rb.equals("m") ? "남자" : "여자";
	
	
	//셀렉트 박스
	String sel1 = request.getParameter("sel1");
	sel1 = sel1.equals("f1") ? "사과" : sel1.equals("f2") ? "바나나" : "귤";
	
	String[] sel2 = request.getParameterValues("sel2");
	
	
	//히든 태그
	String id = request.getParameter("id");
	
	
	//색상, 날짜, 범위
	String color1 = request.getParameter("color1");
	String date1 = request.getParameter("date1");
	String range1 = request.getParameter("range1");
	
	
	//사용자 정의 컨트롤
	String member = request.getParameter("member");
	 
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>

    <h1>데이터 수신 결과</h1>
    
    <table>
        <tr>
            <th>텍스트 박스</th>
            <td><%= txt1 %></td>
        </tr>
        <tr>
            <th>암호 상자</th>
            <td><%= pw1 %></td>
        </tr>
        <tr>
            <th>다중 라인 텍스트</th>
            <td><%= txt2 %></td>
        </tr>
        <tr>
            <th>체크 박스</th>
            <td><%= cb1 %></td>
        </tr>
        <tr>
            <th>체크 박스</th>
            <td><%= cb2 %></td>
        </tr>
        <%-- <tr>
            <th>체크 박스들</th>
            <td><%= tmp %></td>
        </tr> --%>
        <tr>
            <th>체크 박스들</th>
            <td><%= Arrays.toString(cb) %></td>
        </tr>
        <tr>
            <th>라디오 버튼</th>
            <td><%= rb %></td>
        </tr>
        <tr>
            <th>셀렉트 박스</th>
            <td><%= sel1 %></td>
        </tr>
        <tr>
            <th>셀렉트 박스</th>
            <td><%= Arrays.toString(sel2) %></td>
        </tr>
        <tr>
            <th>히든 태그</th>
            <td><%= id %></td>
        </tr>
        <tr>
            <th>색상</th>
            <td><%= color1 %></td>
        </tr>
        <tr>
            <th>날짜</th>
            <td><%= date1 %></td>
        </tr>
        <tr>
            <th>범위</th>
            <td><%= range1 %></td>
        </tr>
        <tr>
            <th>회원</th>
            <td><%= member %></td>
        </tr>
    </table>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

</script>
</body>
</html>

2. response(출력 도구) : HttpServletResponse
        - 서버 -> (행동) -> 클라이언트

    ~ setContentType(type) : 컨텐트 형식 설정
    ~ setHeader(name, value) : 클라이언트에게 헤더로 전달할 값 설정
    ~ setDateHeader(name, date) : 클라이언트에게 헤더로 전달할 날짜 설정
    ~ sendError(status, msg) : 클라이언트에게 에러 코드와 메시지 전달
    ~ sedRedirect(url) : 클라이언트 요청을 다른 페이지로 전달
    ~ addCookie(cookie) : 클라이언트에게 전달할 쿠키 설정
    ~ encodeURL(url) : URL로 유효하지 않은 문자를 인코딩
    ~ setStatus(sc) 상태 코드 설정


3. pageContext
        - 페이지 실행(요청~응답)중에 관련된 데이터를 저장하는 객체
        a. 페이지 이동하기
        
        ~ page.Context.forward(): 데이터를 넘기면서 이동할 때 주로 사용 > 주소 바뀌지 않음
            <-> 일반적으로는 response.sendRedirect() 사용   > 주소 바뀜


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    /*  
    
        서버측 자원의 생명 주기
        - 서블릿 or JSP > 여러 가지 자원 > 언제 생성 ~ 소멸
        - 현재 JSP 페이지가 실행 중일 때 > JSP 페이지 처리 종료 > 자원 소멸
        
    */
    
    int a = 10;
        
    pageContext.setAttribute("b", 20); //pageContext 변수
    request.setAttribute("c", 30); //request 변수
    
    //링크, response.sendRedirect
    //    - 클라이언트측 이동 
    
    //pageContext
    //    - 서버측 이동
    
    /* response.sendRedirect("ex12_pagecontext_two.jsp"); */ //http://localhost:8090/jsp/ex12_pagecontext_two.jsp
    pageContext.forward("ex12_pagecontext_two.jsp"); //http://localhost:8090/jsp/ex12_pagecontext_one.jsp
        
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>

    <h1>첫 번째 페이지</h1>
    
    <div>a: <%= a %></div>
    
    <div>b: <%= pageContext.getAttribute("b") %></div>
    
    <div>c: <%= request.getAttribute("c") %></div>    
    
    <a href="ex12_pagecontext_two.jsp?a=<%= a %>">두 번째 페이지로 이동하기</a>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

</script>
</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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>

    <h1>두 번째 페이지</h1>
    
    <%-- <div>a: <%= a %></div> --%>
    
    <div>a: <%= request.getParameter("a") %></div>    
    
    <div>b: <%= pageContext.getAttribute("b") %></div>
    
    <div>c: <%= request.getAttribute("c") %></div>    
    

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

</script>
</body>
</html>

- out : javax.servlet.jsp.JspWriter
        - 응답 페이지 출력 스트림 객체
        - 서블릿 PrintWriter와 같은 역할
        - out은 메서드를 사용하는 것이 그다지 바람직하지 않음.


<%@ 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>
<link rel="stylesheet" href="https://me2.do/5BvBFJ57">
<style>

</style>
</head>
<body>

    <h1>구구단</h1>
    
    <%
        int dan = 5;
    %>
    
    
    <h2>out 사용 안 함</h2>
    
    <% for(int i=1; i<=9; i++) { %>
    <div><%= dan %> x <%= i %> = <%= dan * i %></div>
    <% } %>
    
    
    <h2>out 사용함</h2>
    
    <%
    for(int i=1; i<=9; i++) {
        out.println(String.format("<div>%d x %d = %d </div>", dan, i, dan*i));
    }    
    %>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>

</script>
</body>
</html>

'서버 > Servlet-JSP' 카테고리의 다른 글

[Servlet-JSP] Redirection  (0) 2023.01.13
JSP 내장 객체 - Session, Application  (0) 2023.01.13
JSP 구성 요소 - 액션 태그  (0) 2023.01.03
JSP 구성 요소 - JSP 지시자  (0) 2023.01.01
JSP 구성 요소 - 스크립트  (0) 2023.01.01