JSP

JSP (예외, pagecontext, ajax, XMLHttpRequest)

code2772 2022. 11. 21. 12:30
728x90
반응형

✔ 원하는 부분 화면에 계속 포함하기

✔ 화면에 다른 파일을 포함하기
   <%@ include file = "화면에 포함할 파일"%>

 

 

 

✔ exception 객체

✔ exception 객체
   - 예외가 발생하면 특정 페이지로 이동
   <%@ page errorPage = "이동할 페이지"%>
   
   - 에러페이지 사용 허용
   <%@ page isErrorPage ="true"%>

 

✔ exception 객체 코드

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%@ page errorPage="2_exception_ok.jsp" %>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>exception 객체</title>
</head>
<body>
   <h2>exception 객체</h2>
   <%
      request.getParameter("text").toString();
   %>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ page isErrorPage = "true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>500 ERROR</title>
<style>
   body{background-color : deepskyblue;}
   h2{font-size : 50px; text-align:center;}
   p{test-align : center;color:gold;}
</style>
</head>
<body>
   <h2>500 ERROR</h2>
   <p>에러타입 : <%= exception.getClass().getName() %></p>
   <p>에러 메세지 : <%=exception.getMessage() %></p>
</body>
</html>

 

✔ exception 객체 결과

 

✔ pageContext 객체

✔ pageContext 객체
   forward()
   - 현재 페이지의 요청과 응답에 관한 제어권을 URL로 지정된 주소로 넘김
   - 제어권만 다른 페이지로 넘기고 URL 주소는 유지되는 방식
   - response.redirect("..") 과는 다름

 

✔ pageContext 객체 코드

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
       session.setAttribute("userid", "apple");
    /*session 값은 넘어가지만 밑에 포월드로 즈소변경한 내용을 활용하고 URL은 유지된다.  */
       pageContext.forward("3_pagecontext_ok.jsp");

    %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>pageContext 객체</title>
</head>
<body>
   <h2>pageContext 객체</h2>
   <p>pageContext의 forward() 예제입니다. 화면에서는 보이지 않습니다.</p>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String userid = request.getParameter("userid");
   String userpw = request.getParameter("userpw");
   
   out.println("아이디는" + userid+ "이며, 비밀번호는" + userpw + "입니다.");
   
%>

 

✔ pageContext 객체 결과

 

✔ Ajax

✔ Ajax(Asynchronous Javascript And XML)
   - 웹 페이지 전체를 다시 로딩하지 않고 웹 페이지의 일부분만을 갱신
   - 백그라운드 영역에서 서버와 통신하여 그 결과를 웹페이지에 표시
   - 서버와 주고 받는 데이터는 JSON, XML, HTML, Text등 사용
   
   🔏 Ajax의 장점
   - 웹페이지 전체를 다시 로딩하지 않아도 웹페이지의 일부분만을 갱신할 수 있음
   - 웹페이지가 모두 로드된 후에도 서버로 데이터를 요청하거나 받을 수 있음
   - 다양한 동적 페이지의 구현이 가능
   
   🔏 Ajax의 단점
   - 페이지 이동이 없기 떄문에 히스토리가 남지 않음
   - 반복적인 데이터를 요청하게 되면 느려지거나 작동하지 않을 수 있음
   - 서버에서 클라이언트로 먼저 요청할 수 없음
   
✔ XMLHttpReques 객체
   - Ajax의 핵심적인 구성 객체
   - 웹 브라우저가 서버와 데이터를 교환할때 사용
   - 백그라운드에서 계속 서버와 통신할 수 있는 기능을 제공
   
   const 변수명 = new XMLHttpRequest();

   
open(전달방식, URL주소, 동기여부) : 서버에 보낼 Ajax 요청의 형식을 설정   
 전달방식 : get, post 방식중 선택
 URL주소 : 요청을 처리할 서버의 파일 주소
 동기여부 : 요청을 동기식으로 전달할지 비동기식으로 전달할지 선택(true : 비동기)
 
 send() : 작성된 Ajax를 서버로 전달
 
 readyState : xhr의 상태를 나타내는 프로퍼티
    0 : 객체생성
    1 : open 메소드 호출
    2 : send 메소드 호출
    3 : loading
    4 : 완료
      
      🔏 onreadystatechange  : readyState의 값이 변할 때마다 호출되는 콜백함수
      
      
   status : xhr이 접속한 서버페이지의 상태
   2xx : 정상적인 호출
   4xx : 페이지 오류

 

✔ Ajax 예제 코드


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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
   <script>
      function sendRequest(){
         const xhr = new XMLHttpRequest();
         xhr.open('get', '4_ajax_ok.jsp?userid=apple&userpw=1234',true);
         xhr.send();

         /* XMLHttpRequest.DONE -> readyState : 4  */
         xhr.onreadystatechange = function(){
            if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200){
               document.getElementById('text').innerHTML = xhr.responseText

            }
         }

      }
   </script>
</head>
<body>
   <h2>Ajax</h2>
   <p><button onclick = "sendRequest()">요청 보내기</button></p>
   <hr>
   <p id ="text"></p>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String userid = request.getParameter("userid");
   String userpw = request.getParameter("userpw");

   out.println("아이디는" + userid+ "이며, 비밀번호는" + userpw + "입니다.");

%>

   
   

 

✔ Ajax 예제 결과 

반응형