JSP - 04

월요일좋아·2022년 10월 26일
0

JSP

목록 보기
4/9
post-custom-banner

액션 태그

setProperty 액션 태그

  • useBean 액션 태그와 함께 자바빈즈의 setter( ) 메소드에 접근하여 자바빈즈의 멤버 변수인 프로퍼티의 값을 저장하는 태그
  • 폼 페이지로부터 전달되는 요청 파라미터의 값을 직접 저장하거나 자바빈즈의 프로퍼티로 변경하여 값을 저장할 수 있음
  • 모든 자바빈즈 프로퍼티 이름과 동일하게 요청 파라미터를 설정할 수 있음
  • setProperty 예제 1
    Person.class
    packagecom.bitc.jspchap07;
    
    public class Person {
    private intid = 20221021;
    privateString name = "홍길동";
    // Alt + Enter : Getter, Setter 쉽게 만들 수 있다.
    publicPerson() {
    
        }
    
    public intgetId() {
    returnid;
        }
    
    public voidsetId(intid) {
    this.id = id;
        }
    
    publicString getName() {
    returnname;
        }
    
    public voidsetName(String name) {
    this.name = name;
        }
    
    }

setProperty.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
    <!DOCTYPE html>
    <html>
    <head>
        <title>액션태그 - setProperty</title>
    
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    <body>
    <jsp:useBean id="person" class="com.bitc.jspchap07.Person" scope="request"></jsp:useBean>
    <jsp:setProperty name="person" property="id" value="20221026"></jsp:setProperty>
    <jsp:setProperty name="person" property="name" value="아이유"></jsp:setProperty>
    <%--세미콜론 빼먹지 말자!--%>
    <%-- setProperty를 사용하면 생성한 값을 useBean을 사용해서 넣는게 가능하다. --%>
    <p>아이디 : <% out.println(person.getId());%></p>
    <p>이름 : <% out.println(person.getName());%></p>
    </body>
    </html>


getProperty 액션 태그

  • 예제 1
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>액션태그 - getProperty</title>
        
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<jsp:useBean id="person" class="com.bitc.jspchap07.Person" scope="request"></jsp:useBean>
        
<%--getProperty 사용법--%>
<p><jsp:getProperty name="person" property="id"/></p>
<p><jsp:getProperty name="person" property="name"/></p>
<%--다른 방법, 동일 결과--%>
<p>아이디: <%=person.getId()%></p>
<p>이름: <%=person.getName()%></p>
</body>
</html>


폼 태그

  • 예제 1
    form01.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>form - 입력 태그</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>회원 가입</h3>
<form action="#" name="member" method="post">
  <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
  <p>비밀번호 : <input type="password" name="passwd"> </p>
  <p>이름 : <input type="text" name="name"></p>
  <p>연락처 : <input type="text" maxlength="4" size="4" name="phone1"> - <input type="text" maxlength="4" size="4" name="phone2"> - <input type="text" maxlength="4" size="4" name="phone3"></p>
  <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
  <input type="radio" name="gender" value="여성">여성</p>
  <p>취미 : 독서<input type="checkbox" name="hobby1" checked>
  운동<input type="checkbox" name="hobby2">
  영화<input type="checkbox" name="hobby3"></p>
  <p><button type="submit">가입하기</button>
  <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>

input 태그

서버로 데이터를 전송하기 위한 유일한 방법

  • text : 한 줄의 텍스트를 입력할 때
  • password : 암호를 입력할 때 사용 ( *** )
  • radio : 단일 선택 → getParameter 로 값 받아주기
  • checkbox : 다중(복수)선택 → getParameterValues 배열로 받아줘야 함
  • file : 파일 업로드를 위한 파일을 선택할 때 사용
  • hidden : 보이지 않게 숨겨서 값을 전송할 때 사용

프로젝트 생성

JSTL 사용법

//
//
//
//
//
//
//


select 태그

  • 예제
    form2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="#" name="member" method="post">
    <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
    <p>비밀번호 : <input type="password" name="passwd"> </p>
    <p>이름 : <input type="text" name="name"></p>
<%--    select 실습 --%>
    <p>연락처 : <select name="phone1">
        <option value="010">010</option>
        <option value="011">011</option>
        <option value="016">016</option>
        <option value="017">017</option>
        <option value="016">016</option></select>
        <input type="text" maxlength="4" size="4" name="phone1"> -
        <input type="text" maxlength="4" size="4" name="phone2"> -
        <input type="text" maxlength="4" size="4" name="phone3">
    </p>

    <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
        <input type="radio" name="gender" value="여성">여성</p>
    <p>취미 : 독서<input type="checkbox" name="hobby1" checked>
        운동<input type="checkbox" name="hobby2">
        영화<input type="checkbox" name="hobby3"></p>
    <p><button type="submit">가입하기</button>
        <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>


textarea 태그

예제
form3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="#" name="member" method="post">
    <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
    <p>비밀번호 : <input type="password" name="passwd"> </p>
    <p>이름 : <input type="text" name="name"></p>
    <%--    select 실습 --%>
    <p>연락처 : **<select name="phone1">
        <option value="010">010</option>
        <option value="011">011</option>
        <option value="016">016</option>
        <option value="017">017</option>
        <option value="016">016</option></select>**
        <input type="text" maxlength="4" size="4" name="phone1"> -
        <input type="text" maxlength="4" size="4" name="phone2"> -
        <input type="text" maxlength="4" size="4" name="phone3">
    </p>

    <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
        <input type="radio" name="gender" value="여성">여성</p>
    <p>취미 : 독서<input type="checkbox" name="hobby1" checked>
        운동<input type="checkbox" name="hobby2">
        영화<input type="checkbox" name="hobby3"></p>

<%-- textarea 실습 --%>
    <p><textarea name="comment" cols="30" rows="3" placeholder="가입 인사를 입력해주세요."></textarea> </p>

    <p><button type="submit">가입하기</button>
        <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>

파라미터

요청 파라미터의 값 받기

• request 내장 객체는 웹 브라우저가 서버로 보낸 요청에 대한 다양한 정보를 담고 있어 getParameter( ) 메소드를 이용하여 요청 파라미터의 값을 얻을 수 있음

예제1
form3.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="form03_process.jsp" name="member" method="post">
    <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
    <p>비밀번호 : <input type="password" name="passwd"> </p>
    <p>이름 : <input type="text" name="name"></p>
    <%--    select 실습 --%>
    <p>연락처 : <select name="phone1">
        <option value="010">010</option>
        <option value="011">011</option>
        <option value="016">016</option>
        <option value="017">017</option>
        <option value="016">016</option></select>
        <input type="text" maxlength="4" size="4" name="phone2"> -
        <input type="text" maxlength="4" size="4" name="phone3">
    </p>

    <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
        <input type="radio" name="gender" value="여성">여성</p>
    <p>취미 : 독서<input type="checkbox" name="hobby1" checked>
        운동<input type="checkbox" name="hobby2">
        영화<input type="checkbox" name="hobby3"></p>

<%-- textarea 실습 --%>
    <p><textarea name="comment" cols="30" rows="3" placeholder="가입 인사를 입력해주세요."></textarea> </p>

    <p><button type="submit">가입하기</button>
        <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>

form3_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  request.setCharacterEncoding("utf-8");

  String id = request.getParameter("id");
  String passwd = request.getParameter("passwd");
  String name = request.getParameter("name");
  String phone1 = request.getParameter("phone1");
  String phone2 = request.getParameter("phone2");
  String phone3 = request.getParameter("phone3");
  String gender = request.getParameter("gender");
  String hobby1 = request.getParameter("hobby1");
  String hobby2 = request.getParameter("hobby2");
  String hobby3 = request.getParameter("hobby3");
  String comment = request.getParameter("comment");
%>

<p>아이디 : <%=id%></p>
<p>비밀번호 : <%=passwd%></p>
<p>이름 : <%=name%></p>
<p>연락처 : <%=phone1 + phone2 + phone3%></p>
<p>성별 : <%=gender%></p>
<p>취미 : <%=hobby1%>, <%=hobby2%>, <%=hobby3%></p>
<p>가입인사 : <%=comment%></p>
</body>
</html>

getParameterValues 예제

form3_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  request.setCharacterEncoding("utf-8");

  String id = request.getParameter("id");
  String passwd = request.getParameter("passwd");
  String name = request.getParameter("name");
  String phone1 = request.getParameter("phone1");
  String phone2 = request.getParameter("phone2");
  String phone3 = request.getParameter("phone3");
  String gender = request.getParameter("gender");
//  String hobby1 = request.getParameter("hobby1");
//  String hobby2 = request.getParameter("hobby2");
//  String hobby3 = request.getParameter("hobby3");

//    배열로 getParameterValues 사용 하는 방법
  **String[] hobby = request.getParameterValues("hobby");**

  String comment = request.getParameter("comment");
%>

<p>아이디 : <%=id%></p>
<p>비밀번호 : <%=passwd%></p>
<p>이름 : <%=name%></p>
<p>연락처 : <%=phone1 + phone2 + phone3%></p>
<p>성별 : <%=gender%></p>

<%--<p>취미 : <%=hobby1%>, <%=hobby2%>, <%=hobby3%></p>--%>
**<p>취미 : <%
    if (hobby != null) {
        for (int i = 0; i < hobby.length; i++) {
            out.print(" " + hobby[i]);
        }
    }
%></p>**

<p>가입인사 : <%=comment%></p>
</body>
</html>

form3.jsp

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2022-10-26
  Time: 오전 10:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="form03_process.jsp" name="member" method="post">
    <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
    <p>비밀번호 : <input type="password" name="passwd"> </p>
    <p>이름 : <input type="text" name="name"></p>
    <%--    select 실습 --%>
    <p>연락처 : <select name="phone1">
        <option value="010">010</option>
        <option value="011">011</option>
        <option value="016">016</option>
        <option value="017">017</option>
        <option value="016">016</option></select>
        <input type="text" maxlength="4" size="4" name="phone2"> -
        <input type="text" maxlength="4" size="4" name="phone3">
    </p>

    <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
        <input type="radio" name="gender" value="여성">여성</p>
    <p>취미 : 독서<input type="checkbox" name="hobby" checked value="독서">
        운동<input type="checkbox" name="hobby" value="운동">
        영화<input type="checkbox" name="hobby" value="영화"></p>

<%-- textarea 실습 --%>
    <p><textarea name="comment" cols="30" rows="3" placeholder="가입 인사를 입력해주세요."></textarea> </p>

    <p><button type="submit">가입하기</button>
        <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>

폼 데이터 일괄처리

폼 데이터의 일괄 처리 메소드

예제1
form04.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="form04_process.jsp" name="member" method="post">
    <p>아이디 : <input type="text" name="id"><button type="button"> 아이디 중복 검사</button></p>
    <p>비밀번호 : <input type="password" name="passwd"> </p>
    <p>이름 : <input type="text" name="name"></p>
    <%--    select 실습 --%>
    <p>연락처 : <select name="phone1">
        <option value="010">010</option>
        <option value="011">011</option>
        <option value="016">016</option>
        <option value="017">017</option>
        <option value="016">016</option></select>
        <input type="text" maxlength="4" size="4" name="phone2"> -
        <input type="text" maxlength="4" size="4" name="phone3">
    </p>

    <p>성별 : <input type="radio" name="gender" value="남성" checked> 남성
        <input type="radio" name="gender" value="여성">여성</p>
    <p>취미 : 독서<input type="checkbox" name="hobby" checked value="독서">
        운동<input type="checkbox" name="hobby" value="운동">
        영화<input type="checkbox" name="hobby" value="영화"></p>

    <%-- textarea 실습 --%>
    <p><textarea name="comment" cols="30" rows="3" placeholder="가입 인사를 입력해주세요."></textarea> </p>

    <p><button type="submit">가입하기</button>
        <button type="reset">다시쓰기</button> </p>
</form>
</body>
</html>

form04.jsp

<%@ page import="java.util.Enumeration" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page import="java.util.Enumeration" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<table border="1">
  <tr>
    <th>요청 파라미터 이름</th>
    <th>요청 파라미터 값</th>
  </tr>
  <%
    request.setCharacterEncoding("UTF-8");

//    Enumeration : 열거형
    Enumeration paramNames = request.getParameterNames();

    while (paramNames.hasMoreElements()) {
//      .toString();
      String name = paramNames.nextElement().toString();
//      강제 형변환 해줘도 됨
//      String name = (String) paramNames.nextElement();

      out.print("<tr><td>" + name + "</td>\n");
      String paramValue = request.getParameter(name);
      out.print("<td>" + paramValue + "</td></tr>\n");
    }
  %>
</table>
</body>
</html>


세션

서버의 저장공간.

오직 웹 서버에 존재하는 공간, 클라이언트(웹 브라우저)마다 하나씩 존재 → 웹서버에 접속중인 사용자를 구분하는 단위가 됨

웹 브라우저를 닫기 전에 웹페이지를 이동하더라도 그대로 서버에 저장이 되어있음

  • sessoion 내장 객체 메소드의 종류

setMaxInactiveInterval : 세션 유지시간 ← 초 단위!

name : 세션의 이름(값을 받아오기 위한 키로 사용)

value : 속성값(실제 데이터를 넣는 부분) - 보통 String 타입으로 넣는다.


세션 예제 1

chap10
session01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="session01_process.jsp" method="post">
    <label for="userId">아이디 : </label>
    <input type="text" id="userId" name="userId" placeholder="아이디를 입력하세요"><br>
    <label for="userPw">비밀번호</label>
    <input type="text" id="userPw" name="userPw" placeholder="비밀번호를 입력하세요"><br>
    <button type="submit">전송</button>
</form>
</body>
</html>

session01.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  String userid = request.getParameter("userId");
  String userpw = request.getParameter("userPw");

  if (userid.equals("admin") && userpw.equals("1234")) {
    session.setAttribute("userId", userid);
    session.setAttribute("userPw", userpw);
    out.println("세션 설정이 성공했습니다.");
    out.println(userid + "님 환영합니다.");
  }
  else {
    out.println("세션 설정이 실패했습니다.");
  }
%>
</body>
</html>


세션 예제 2

session02.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
//  String userId = session.getAttribute("userId").toString();
//  String userPw = session.getAttribute("userPw").toString();

    String userId = (String)session.getAttribute("userId");
    String userPw = (String)session.getAttribute("userPw");

  out.println("설정된 세션의 속성 값 : " + userId + "<br>");
  out.println("설정된 세션의 속성 값 : " + userPw + "<br>");
%>
</body>
</html>


저장된 값이 없어서 둘 다 null이 뜸

session01 열어서 데이터 넣고 실행 후 session02로 다시 돌아오면

session02에도 값이 들어있음.

💡 why?
웹 - 각각의 페이지는 각각의 어플리케이션이고 각각의 웹 페이지는 기본적으로 데이터를 공유하지 않는다
세션이라고 하는것은 동일한 세션 아이디일때 웹 서버 내에 저장공간을 마련하여 웹 서버와 접속이 끊어지기 전까지 계속 유지. 다른 페이지로 이동해도 세션에 저장된 데이터는 공유가 된다.
(크롬을 다 닫으면 접속이 끊어지는것. → 다시 새로 열면 새로운 세션 아이디 생성)


다중 세션 정보 얻기

getAttributeNames() 사용 예

다중 세션 예제 1

session03.jsp

<%@ page import="java.util.Enumeration" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  String name;
  String value;

//  Enumeration 타입으로 데이터를 받을 경우 원하는 데이터 타입을 설정할 수 있음 ex) <String>
  Enumeration<String> en = session.getAttributeNames();
//  타입 미설정 시 Object 타입
//  Enumeration en = session.getAttributeNames();
  int i = 0;

  while (en.hasMoreElements()) {
    i++;
    name = en.nextElement();
    value = session.getAttribute(name).toString();

    out.println("설정된 세션의 속성 이름 : [" + i + "] : " + name + "<br>");
    out.println("설정된 세션의 속성 값 : [" + i + "] : " + value + "<br>");
  }
%>
</body>
</html>


단일 세션 삭제하기

세션 삭제 예제 1

session04.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>----- 세션을 삭제하기 전 -----</h3>
<%
    String userId = (String) session.getAttribute("userId");
    String userPw = (String) session.getAttribute("userPw");
    out.println("설정된 세션 이름 userId " + userId + "<br>");
    out.println("설정된 세션 값 userPw " + userPw+ "<br>");

    **session.removeAttribute("userId");**
%>
<br>
<h3>----- 세션을 삭제한 후 -----</h3>
<%
    userId = (String) session.getAttribute("userId");
    userPw = (String) session.getAttribute("userPw");
    out.println("설정된 세션 이름 userId : " + userId + "<br>");
    out.println("설정된 세션 값 userPw : " + userPw + "<br>");

%>
</body>
</html>


다중 세션 삭제하기

세션에 저장된 모든 세션 속성 이름을 삭제하려면 invalidate( ) 메소드를 사용

session05.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>------ 세션 삭제 전 ------</h3>
<%
    String userId = (String) session.getAttribute("userId");
    String userPw = (String) session.getAttribute("userPw");
    out.print("설정된 세션 이름 userId : " + userId + "<br>");
    out.print("설정된 세션 값 userPw : " + userPw + "<br>");

    if (request.isRequestedSessionIdValid() == true) {
        out.print("세션이 유요합니다.");
    }
    else {
        out.println("세션이 유효하지 않습니다.");
    }

    session.invalidate();
%>
<br>
<h3>------ 세션 삭제 후 ------</h3>
<%
    if (request.isRequestedSessionIdValid() == true) {
        out.print("세션이 유효합니다.");
    }
    else {
        out.print("세션이 유효하지 않습니다.");
    }
%>
</body>
</html>

예제 실행

  1. session02 실행해서 현재 값 확인 하고 session01 실행
  2. session01에 admin, 1234 넣어서 값 넣어준다음에 session05 실행해서 확인


세션 유효시간 설정

기본적으로 초 단위.

세션 유효 시간을 설정하기 위해 session 내장 객체의 **setMaxInactiveInterval( )** 메소드를 사용

세션 유효시간 설정 예제 1

session06.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>세션 사용하기</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>----- 세션 유효 시간 변경 전 -----</h3>
<%
  int time = session.getMaxInactiveInterval() / 60; // 기본설정이 `초`단위라서 분 단위로 바꿔주기위해 나누기 60
  out.println("세션 유효 시간 : " + time + "분<br>");
%>
<br>
<h3>----- 세션 유효 시간 변경 후 -----</h3>
<%
  session.setMaxInactiveInterval(24 * 60 * 60); // 1분이 60초니까 60 * 60은 1시간, 거기에 (* 24)는 하루가 됨
  time = session.getMaxInactiveInterval() / 60;
  out.println("세션 유효 시간 : " + time + "분<br>");
%>
</body>
</html>


세션 유효 시간 설정 예제 2

session07.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>세션 사용하기</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<br><br>
<form action="session07_process.jsp" method="post">
  <label for="user-name">이름 : </label>
  <input type="text" id="user-name" name="userName" placeholder="이름을 입력하세요"><br>
  <label for="user-email">이메일 : </label>
  <input type="email" id="user-email" name="userEmail" placeholder="이메일을 입력하세요"><br>
  <label for="user-phone">전화번호 : </label>
  <input type="text" id="user-phone" name="userPhone" placeholder="전화번호를 입력하세요"><br><br>
  <button type="submit">전송</button>
  <br>
  <a href="session07_result.jsp">확인 페이지로</a>
</form>

</body>
</html>

session07_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>세션 사용하기</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  request.setCharacterEncoding("UTF-8");
  String userName = request.getParameter("userName");
  String userEmail = request.getParameter("userEmail");
  String userPhone = request.getParameter("userPhone");

  session.setAttribute("userName", userName);
  session.setAttribute("userEmail", userEmail);
  session.setAttribute("userPhone", userPhone);

  session.setMaxInactiveInterval(5); // 5초

  response.sendRedirect("session07_result.jsp"); // 해당 페이지로 강제로 이동시킴
%>
</body>
</html>

session07_result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>세션 사용하기</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  request.setCharacterEncoding("UTF-8");
  String userName = (String) session.getAttribute("userName");
  String userEmail = (String) session.getAttribute("userEmail");
  String userPhone = (String) session.getAttribute("userPhone");
%>

<p>이름 : <%=userName%></p>
<p>이메일 : <%=userEmail%></p>
<p>전화번호 : <%=userPhone%></p>

<br>
<br>
<a href="session07.jsp" alt="">이전 페이지로</a>
</body>
</html>


session07 → 확인 페이지로 클릭

확인 : 데이터 없음

데이터 입력 후 전송

값이 들어와있는것 확인 가능

5초 후 데이터 리셋


예외처리(Chap.09)

예외처리 : chap09

새 프로젝트 생성시 gradle 파일에 2줄 추가해주기!

예외처리 방법과 종류

errorPage 속성으로 오류 페이지 호출하기

예제 1
errorPage.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
**<%@ page errorPage="errorPage_error.jsp" %>**
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
**<%-- 일부러 에러 발생시킴 --%>
<p>name 파라미터 : <%=request.getParameter("name").toUpperCase()%></p>**
</body>
</html>

errorPage_error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>오류가 발생했습니다.</h3>
</body>
</html>


isErrorPage

  • isErrorPage 속성
    • 현재 JSP 페이지를 오류 페이지로 호출하는 page 디렉티브 태그의 속성
    • 이때 오류 페이지에서 exception 내장 객체를 사용할 수 있음

예제 1

isErrorPage.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page errorPage="isErrorPage_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%-- 일부러 에러 발생시킴 --%>
<p>name 파라미터 : <%=request.getParameter("name").toUpperCase()%></p>
</body>
</html>

isErrorPage_error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%-- true 일때 exception 내장객체에서 값 받아올 수 있음 --%>
<%@ page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p>오류가 발생하였습니다.</p>
<p>예외 유형 : <%=exception.getClass().getName()%></p>
<p>오류 메시지 : <%=exception.getMessage()%></p>
</body>
</html>


예제 2

exception.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="exception_process.jsp" method="post">
  <p>숫자 1 : <input type="text" name="num1"></p>
  <p>숫자 2 : <input type="text" name="num2"></p>
  <button type="submit">나누기</button>
</form>
</body>
</html>

exception_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@ page errorPage="exception_error.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  String num1 = request.getParameter("num1");
  String num2 = request.getParameter("num2");
  int a = Integer.parseInt(num1);
  int b = Integer.parseInt(num2);

  int c = a / b;
  out.print(num1 + " / " + num2 + " = " + c);
%>
</body>
</html>

exception_error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%@page isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p>오류가 발생했습니다.</p>
<p>예외 : <%=exception%></p>
<p>toString() : <%=exception.toString()%></p>
<p>getClass().getName() : <%=exception.getClass().getName()%></p>
<p>getMessage() : <%=exception.getMessage()%></p>
</body>
</html>


web.xml 파일을 이용한 예외 처리

web.xml 파일의 위치


web.xml 파일에 오류 코드와 오류 페이지를 설정하는 형식

  • 오류 코드의 종류

401 : 서버에서 거부

404 : 데이터가 없음

500 : 서버에 접근은 성공, 서버 내부에서 오류

web.xml

예제1

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    예제 1    -->
    <error-page>
        <error-code>500</error-code>
        <location>/error/errorCode500.jsp</location>
    </error-page>
</web-app>

errorCode.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="errorCode_process.jsp" method="post">
  <p>숫자 1 : <input type="text" name="num1"></p>
  <p>숫자 2 : <input type="text" name="num2"></p>
  <button type="submit">나누기</button>
</form>
</body>
</html>

errorCode_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%-- errorPage = ""  <- 에러페이지 설정 부분이 없음. --%>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  String num1 = request.getParameter("num1");
  String num2 = request.getParameter("num2");
  int a = Integer.parseInt(num1);
  int b = Integer.parseInt(num2);
  int c = a / b;
  out.print(num1 + " / " + num2 + " = " + c);
%>
</body>
</html>

/error/errorCode500.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>Error Code 500 에러가 발생했습니다.</h3>
</body>
</html>

해당 예제 실행하기 위해서는 무조건 서버 재시작 해줘야 함! (xml 파일 리로드)

? 에러페이지 설정 없이도 errorCode500.jsp가 실행되는 이유 ?

  • web.xml에tj 500에러 발생 시 errorCode500.jsp를 실행하도록 설정해두었기 때문.
  • web.xal과 errorPage 설정이 모두 되어있을때 우선순위는 errorPage 설정이다.


주요 예외 유형의 종류


예외처리 예제 1

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    예제 1    -->
    <error-page>
        <error-code>500</error-code>
        <location>/error/errorCode500.jsp</location>
    </error-page>
    
<!--    예제 2    -->
    <error-page>
        <exception-type>java.lang.ArithmeticException</exception-type>
        <location>/error/exceptionTypeArithmetic.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.ArrayIndexOutOfBoundsException</exception-type>
        <location>/error/exceptionTypeArrayIndexOutOfBound.jsp</location>
    </error-page>
</web-app>

exceptionTypeArrayIndexOutOfBound.jsp

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>ArrayIndexOutOfBoundException 예외가 발생했습니다.</h3>
<p>종류 : <%=exception.getClass().getName()%></p>
<p>메시지 : <%=exception.getMessage()%></p>
</body>
</html>

exceptionTypeArithmetic

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<h3>exceptionTypeArithmetic 예외가 발생했습니다.</h3>
<p>종류 : <%=exception.getClass().getName()%></p>
<p>메시지 : <%=exception.getMessage()%></p>
</body>
</html>

exceptionType_process

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

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  String num1 = request.getParameter("num1");
  String num2 = request.getParameter("num2");
  String num3 = request.getParameter("num3");
  int a = Integer.parseInt(num1);
  int b = Integer.parseInt(num2);
  int c = a / b;
  int index = Integer.parseInt(num3);
  out.print(num1 + " / " + num2 + " = " + c);

  int[] array = {1, 2, 3, 4, 5};
  out.print("선택한 index의 값 : " + array[index]);

%>
</body>
</html>

exceptionType

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Title</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="exceptionType_process.jsp" method="post">
  <label for="num1">숫자1 : </label>
  <input type="text" id="num1" name="num1"><br>
  <label for="num2">숫자2 : </label>
  <input type="text" id="num2" name="num2"><br>
  <label for="num3">0~4</label>
  <input type="text" id="num3" name="num3"><br>
  <button type="submit">나누기</button>
</form>
</body>
</html>

try-catch-finally를 이용한 예외 처리

자바와 동일하게 사용할 수 있음.

  • RequestDispatcher : 클라이언트에서 최초로 들어온 요청을 jsp/Servlet 내에서 원하는 곳으로 요청을 넘기고 처리 결과를 받아오는 클래스
  • 우선순위 : try~Catch > errorpage 속성 > xml 파일 속성

예제 1
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    예제 1    -->
    <error-page>
        <error-code>500</error-code>
        <location>/error/errorCode500.jsp</location>
    </error-page>
    
<!--    예제 2    -->
    <error-page>
        <exception-type>java.lang.ArithmeticException</exception-type>
        <location>/error/exceptionTypeArithmetic.jsp</location>
    </error-page>
    <error-page>
        <exception-type>java.lang.ArrayIndexOutOfBoundsException</exception-type>
        <location>/error/exceptionTypeArrayIndexOutOfBound.jsp</location>
    </error-page>
</web-app>

tryCatch.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<form action="tryCatch_process.jsp" method="post">
  <label for="num1">숫자 1 : </label>
  <input type="text" id="num1" name="num1"><br>
  <label for="num2">숫자 2 : </label>
  <input type="text" id="num2" name="num2"><br>
  <button type="submit">나누기</button>
</form>
</body>
</html>

tryCatch_process.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<%
  try {
    String num1 = request.getParameter("num1");
    String num2 = request.getParameter("num2");
    int a = Integer.parseInt(num1);
    int b = Integer.parseInt(num2);
    int c = a / b;
    out.print(num1 + " / " + num2 + " = " + c);
  }
  **// xml 보다 우선순위가 높음
  catch** **(Exception e)** {
    **// 이동할 페이지를 설정
    RequestDispatcher dispatcher = request.getRequestDispatcher("tryCatch_error.jsp");
    // 설정된 페이지로 이동
    dispatcher.forward(request, response);**
  }
%>
</body>
</html>

tryCatch_error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>예외처리</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p>잘못된 데이터가 입력되었습니다.</p>
<p><%="숫자 1 : " + request.getParameter("num1")%></p>
<p><%="숫자 2 : " + request.getParameter("num2")%></p>
</body>
</html>

post-custom-banner

0개의 댓글