티스토리 뷰

1.    JSP 내장 객체 ( implicit, Object, 내장 변수 )

-      내장 객체는 JSP 페이지가 서블릿으로 변환될 때, 자동으로 추가해주는 객체를 의미

-      항상 고정된 값으로 제공되기 때문에 JSP페이지에서 선언 없이 사용이 가능하지만, 지정된 변수 값으로만 사용해야 한다.

-      내장 객체는 _jspService 메소드 내에서 선언된 변수이기 때문에 Scriptlet 태그나 Expression 태그에서만 사용이 가능하다.

 

2.    내장객체 종류

-      1 ) request : HttpServletRequest 객체 참조

-      2 ) response : HttpServletResponse 객체 참조

-      3 ) out : 웹 브라우저 출력 ( JspWriter 객체 )

-      4 ) session : HttpSession 객체 참조

-      5 ) application : ServletContext 객체 참조

-      6 ) config : ServletConfig 객체 참조

-      7 ) page : 자바 클래스의 this

-      8 ) exception : 예외처리 ( isErrorPage="true" 인 경우에만 )

 

3.    웹 어플리케이션의 예외처리 방법

-      1 ) <% @ page %> 지시어의 "errorPage" "isErrorPage" 속성을 이용한, 개별 예외처리 방식

-      2 ) web.xml 을 이용하여, 응답코드(HTTP status code)별 예외처리 페이지 지정방식

-      3 ) web.xml 을 이용하여, 예외타입( : java.lang.NullPointerException)별 예외처리 페이지 지정방식

-      + 1번 방식이 가장 우선적으로 적용되며, 실전에서는 2번이 가장 중요하다.


[ 1. 내장객체 사용해 보기 - 로그인 ]

 

[ 1 - 1. 로그인 폼 화면 만들기 ]

 

<!DOCTYPE html>

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <!-- 정적 문서파일은 webapp 파일 밑에 생성해야 한다. -->
</head>

<body>
    <h1>getParameter 실습</h1>

    <form action="JSP/LoginInfo.jsp" method="get">

        <fieldset>

            <legend>로그인 폼</legend>
            
            <ul>
                <li>
                    <label for="userid">1. 아이디</label>
                    <input type="text" name="userid">
                </li>

                <li>
                    <label for="password">2. 비밀번호</label>
                    <input type="password" name="password">
                </li>

                <li><input type="submit" value="전송"></li>
            </ul>
        </fieldset>
    </form>
</body>

</html>

[ 1 - 2. 내장객체를 활용해서 입력한 값 얻어내기 ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>LoginInfo.jsp - 내장객체 실습</title>
</head>

<body>
    
    <h1>LoginInfo.jsp - 내장객체 실습</h1>
    <h1>로그인 입력 파라미터 출력</h1>

    <hr>

    <!-- scriptlet Tag -->
    <%
    
        // request 내장객체
        request.setCharacterEncoding("UTF-8");

        String userid = request.getParameter("userid");
        String password = request.getParameter("password");

        // 응답문서에 출력
        out.println("1. userid : " + userid);
        out.println("2. password : " + password);

        // 콘솔에 출력
        System.out.println("1. userid : " + userid);
        System.out.println("2. password : " + password);

        // 롬복이 사용이 불가능하기에, log도 사용이 불가능하다.
    
    %>

    <!-- Expression Tag -->
    <p>1. 아이디 값 : <%= userid %> </p>
    <p>2. 비밀번호 값 : <%= password %> </p>

</body>

</html>

[ 2. 내장 객체 2 - response - response.sendRedirect( " target " ); ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ResposeRedirect.jsp</title>
</head>

<body>
    <h1>ResposeRedirect.jsp</h1>

    <hr>

    <h2>responseRedirect.jsp에 의해 redirect된 화면입니다.</h2>
</body>

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>response.jsp</title>
</head>

<body>

    <!-- 요청을 target으로 다시 보내게 한다. -->
    <!-- 즉, response.jsp를 런 온 서버를 하면, responseRedirect.jsp로 바로 이동하게 된다. -->
    <% response.sendRedirect("responseRedirect.jsp"); %>
    
</body>

</html>

[ 3. 내장 객체 3 - out - out.println ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>out.jsp - 내장객체 out</title>
</head>

<body>
    <h1>out.jsp - 내장객체 out</h1>
    
    <hr>

    <%
    
        String name = "홍길동";

        out.println(String.format( "<p>1. 이것은 out 내장객체로 출력 : %s </p>", name ) );
    
    %>

    <p>2. 이것은 Expression 태그로 출력 : <%= name %></p>

</body>

</html>

[ 4. 내장 객체 4 - config - 초기화 파라미터 값 얻어내기 - config.getInitParameter(" 파라미터 이름 "); ]

 

[ 4 - 1. web.xml 파일에 JSP 초기화 파라미터 등록하기 ]

 

 <!-- JSP의 초기화 파라미터 등록 -->

    <servlet>

      <servlet-name>configJSP</servlet-name>
      <jsp-file>/JSP/config.jsp</jsp-file>

      <init-param>
        <param-name>dirPath</param-name>
        <param-value>C:/Temp/upload</param-value>
      </init-param>

      <init-param>
        <param-name>userid</param-name>
        <param-value>wow</param-value>
      </init-param>

    </servlet>

    <servlet-mapping>
      <servlet-name>configJSP</servlet-name>
      <url-pattern>/JSP/config.jsp</url-pattern>
      <url-pattern>/CONFIG</url-pattern>
    </servlet-mapping>

[ 4 - 2. JSP에서 초기화 파라미터 값 얻어내기 ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>config.jsp</title>
</head>

<body>
   <h1>/JSP/config.jsp</h1>
   
   <hr>

   <h2>config 내장객체를 이용한 초기화 파라미터 값 얻어내기</h2>

   <%
   
    // Scriptlet : 자바 실행문장을 얼마든지 만들 수 있는 JSP 태그
    String dirPath = config.getInitParameter("dirPath");
    String userid = config.getInitParameter("userid");
   
   %>

   <ol>
       <li> dirPath : <%= dirPath %> </li>
       <li> userid : <%= userid%> </li>
   </ol>

</body>

</html>

[ 5. 내장 객체 5 - ServletContext application - 방문자 수 카운트 - application.setAttribute("속성이름", 속성값); ] (***)

 

[ 5 - 1. Application Scope에 방문자수를 카운트해서 공유데이터 올려 놓기 ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>count.jsp</title>

    <style>

        h2{
            color: lightslategrey;
            font-size: 3em;
            border-bottom: 3px double lightcoral;
            text-align: center;
        }

    </style>

</head>

<body>
    <h1>/JSP/count.jsp</h1>
    <hr>

    <h2>방문자수 설정하기 화면</h2>

    <!-- 선언으로 필드 생성 -->
    <%! int count; %>

    <!-- Scriptlet tag -->
    <%
    
        count ++;

        // Application 공유 데이터 영역에 count 올려 놓기
        // Scriptlet tag는 service와 같이 실행될때마다 실행되기에 방문자수가 올라간다.
        // 이때 count에는 Object 타입이 와야 하는데, int가 Integer로 오토박싱된 것이다.
        application.setAttribute("countValue", count);
    
    %>

    <!-- 이거는 Application 영역에 올려 놓은 데이터를 활용한 것이 아니라, 지역변수를 활용한 것이다. -->
    <h2>방문자수 : <%= count%> </h2>

</body>

</html>

 

[ 5 - 2. Application Scope에서 방문자수 데이터 가지고 오기 ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>countInfo.jsp</title>
</head>

<body>
    <h1>/JSP/countInfo.jsp</h1>
    <hr>

    <h2>방문자수 조회하기 화면</h2>

    <%
    
        // Application scope에서 countValue(방문자수)라는 이름의 공유 데이터를 얻음
        // getAttribute로 얻으면 Object 객채로 반환되기에, 형변환시켜줘야 한다.
        int visitors = (Integer) application.getAttribute("countValue");
    
    %>

    <p>현재까지 총 방문자수 : <%= visitors %> </p>

</body>

</html>

[ 6. 내장 객체 6 - session - session.setAttribute("속성이름", 속성값); - 로그인 / 로그아웃 기능 ] (***)

 

[ 6 - 1. 로그인 창 생성 ]

 

<!DOCTYPE html>

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>

    <!-- 정적 문서파일은 webapp 파일 밑에 생성해야 한다. -->
</head>

<body>
    <h1>getParameter 실습</h1>

    <form action="JSP/login.jsp" method="post">

        <fieldset>

            <legend>로그인 폼</legend>
            
            <ul>
                <li>
                    <label for="userid">1. 아이디</label>
                    <input type="text" name="userid">
                </li>

                <li>
                    <label for="password">2. 비밀번호</label>
                    <input type="password" name="password">
                </li>

                <li><input type="submit" value="전송"></li>
            </ul>
        </fieldset>
    </form>
</body>

</html>

 

[ 6 - 2. 로그인 확인 페이지 생성 - 로그인 정보를 Session Scope에 저장 ]

 

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

<%
    
    // Step 1
    request.setCharacterEncoding("utf8");

    String userid = request.getParameter("userid");
    String password = request.getParameter("password");

    // Step 2 - 무조건 로그인 처리
    // 단, 아이디와 비번이 정상 수신될 경우에만

    if( ( userid != null && !"".equals(userid) ) &&  ( password != null && !"".equals(password) ) ){ 

        // 로그인이 된 상태일때

        System.out.println(">>>>>>>> 로그인되었습니다!! <<<<<<<<");
        // 로그인 정보를 보여준다.

    } else {

        // 로그인이 되지 않은 상태일때

        response.sendRedirect("/LoginForm.html");
        // 만약 로그인이 되지 않은 상태라면 로그인 창으로 이동

        System.out.println(">>>>>>>> 로그인 창으로 이동 : sendRedirect!! <<<<<<<<");
        // 로그인 창으로 이동

        return;
        // return을 사용하여 로그인이 되지 않은 상태이면, 더 이상의 메소드의 실행을 막아버린다. (***)

    } // if - else

    // Step 3
    // 로그인이 성공한다면 무엇을 해야 되는가?
    // 현재 로그인 한 웹 브라우저와 생명주기가 동일한 Session Scope에
    // Login Succed 정보를 올려 놓아야 한다.

    session.setAttribute("userid", userid);
    session.setAttribute("password", password);

%>

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>login.jsp"</title>
</head>

<body>
    
    <h1>/JSP/login.jsp"</h1>
    <hr>

    <h2>로그인 정보를 Session Scope에 저장</h2>

    <ul>
        <li>안녕하세요! <%= userid %></li>
        <li> <a href="/JSP/loginInfo2.jsp">로그인 정보보기</a> </li>
    </ul>

</body>

</html>

 

[ 6 - 3. 로그인 정보 페이지 생성 - 로그인 정보를 Session Scope에서 불러온다. ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>/JSP/LoginInfo2.jsp</title>
</head>

<body>
    
    <h1>/JSP/LoginInfo2.jsp</h1>
    <hr>

    <h2>로그인 정보 알아보러 가기</h2>

    <%
    
        // 현재의 웹 브라우저가 로그인에 성공한 브라우저인지 아닌지 판단
        // 로그인에 성공한 웹 브라우저라면, 로그아웃이라는 링크를 생성

        // Step1. Session scope에서 성공 로그인정보(id, password)를 획득
        // 만일 없으면, 리다이렉션을 통해서 로그인 창으로 밀어낸다.

        String userid = (String) session.getAttribute("userid");
        String password = (String) session.getAttribute("password");

        if( userid != null && password != null ){ // 로그인 성공정보가 유효하다면
    %>

    <p> 1. userid : <%= userid%> </p>
    <p> 2. password : <%= password%> </p>
    <h2> <a href="/JSP/logout.jsp">로그아웃</a></h2>

    <%
    
        } else { // 성공 로그인 정보가 없다면

            response.sendRedirect("/LoginForm.html");
            System.out.println(">>>>Re-directed<<<<");

            return;

        } // if - else
    
    %>
</body>

</html>

 

[ 6 - 4. 로그아웃 페이지 생성 - Session Scope 파괴함으로써 로그인 정보 삭제 ]

 

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

<%
    
    // 1. 해당 브라우저에 할당된 Session Scope 파괴
    session.invalidate();

    // 2. 로그아웃 처리 후에, 웹 브라우저는 어디로 이동해야 되는지 지정 ( Re-direct )
    response.sendRedirect("/LoginForm.html");

    // + Forward
    // RequestDispatcher dis = request.getRequestDispatcher("/LoginForm.html");
    // dis.forward(request, response);

%>

<script>
    alert('정상적으로 로그아웃 처리 되었습니다.');
</script>

<% return; %>
<!-- return은 어차피 가장 마지막에 수행되기에, 지워도 괜찮다. -->

[ 7. 내장 객체 7 - exception - 예외처리 기능 ( 공통속성이 아니다. ) ] (***)

 

[ 7 - 1. 에러를 발생할 JSP 생성 ] 

 

<%@ page 
    language="java" 
    isErrorPage = "false"
    errorPage = "/JSP/error.jsp"
    contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%

    int n = 4 / 0;
    // 오류가 발생되는 코드이다.
    // isErrorPage = "true";를 작성해 줘야만 exception 내장객체를 사용할 수 있다.
    // 또한 errorPage = "에러처리jsp"로 이 페이지에서 오류가 발생하면 어느 곳에서 예외를 처리할지 정해야 한다.

%>

 

[ 7 - 2. 에러를 처리할 JSP 생성 ] 

 

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

<!-- 이 JSP는 다른 JSP에서 발생하는 예외(Exception)를 내장객체인 exception으로 받아서 -->
<!-- 예외처리하는 역할을 수행한다. ( isErrorPage = "true"일 경우!!! ) -->

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>error.jsp</title>
</head>

<body>
    <h1>/JSP/error.jsp</h1>
    <hr>

    <h2>divide.jsp에서 발생한 예외를 처리하는 페이지</h2>

    <h1>고객 센터로 문의해주시기를 바랍니다.</h1>
    <p>잠시 시스템에 문제가 발생했습니다.</p>
    <p>잠시 후에 다시 시도해주시길 바랍니다.</p>

    <hr>

    <h2><%= exception.getClass() %> : <%= exception.getLocalizedMessage() %></h2>

    <hr>

    <ol>

    <%

        StackTraceElement [] ste = exception.getStackTrace();

        for( StackTraceElement element : ste ) {
    
    %>
        <li><%= element %></li>
    
    <%
    
        } // enhanced for
    
    %>


    </ol>

</body>

</html>

[ 8. 웹 어플리케이션의 예외처리방법 - web.xml파일에서 지정하는 방법 ] (*****)

 

[ 8 - 1. web.xml에서 예외처리할 jsp를 지정 ]

 

<!-- Web Application의 예외처리 방법 1 -->

    <error-page>
      <error-code>500</error-code>
      <location>/JSP/error/500.jsp</location>
    </error-page>

    <error-page>
      <error-code>404</error-code>
      <location>/JSP/error/404.jsp</location>
    </error-page>

    <!-- Web Application의 예외처리 방법 2 -->

    <error-page>
      <exception-type>java.lang.NullPointerException</exception-type>
      <location>/JSP/error/null.jsp</location>
    </error-page>

 

[ 8 - 2. 예외처리를 할 jsp 생성 ]

 

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

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>500</title>
</head>

<body>
    
    <h1>/JSP/error/500.jsp</h1>
    <hr>
    
</body>

</html>

 

 

728x90
댓글
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
최근에 올라온 글
Total
Today
Yesterday
공지사항