16. 자바 빈
0. 목차
Chapter16. 자바 빈
Ch16 - 1. 빈 이란?
Ch16 - 2. 빈 만들기
Ch16 - 3. 빈 관련 액션 태그(useBean, getProperty, setProperty)
Ch16 - 1. 빈 이란?
▶ 빈 이란?
▷ JAVA 언어의 데이터(속성)와 기능(메소드)으로 이루어진 클래스
▷ 반복적인 작업을 효율적으로 하기 위해 빈 사용
- java에서 반복적인 작업을 할 때 클래스 사용 한 것처럼
- jsp는 빈을 클래스처럼 사용하는 것
- java에서 만든 데이터 객체를 jsp에서는 빈이라고 함
▶ 빈 사용 방법
▷ jsp 페이지를 만들고, 액션 태그를 이용하여
- 빈을 사용하고,
- 빈의 내부 데이터도 처리
Ch16 - 2. 빈 만들기
▶ 빈 생성
▷ 빈 : 데이터 객체 클래스
▷ 데이터 객체에는 데이터가 있어 그에 해당하는 getter와 setter가 있음
Ch16 - 3. 빈 관련 액션 태그
▶ useBean
▷ 특정 bean을 사용한다고 명시 할 때 사용
// <jsp:useBean id="빈 이름" class="클래스의 패키지 경로.클래스 이름" scope="스코프 범위" />
<jsp:useBean id="student" class="com.javalec.ex.Student" scope="page" />
// 클래스에서 데이터 객체 사용
Student student = new Student();
// 빈에서 데이터 객체 사용
id="student"
- Scope란?
- page : 생성 된 페이지 내에서만 사용 가능
- request : 요청된 페이지 내에서만 사용 가능
- session : 웹 브라우저의 생명 주기와 동일하게 사용 가능
- application : 웹 어플리케이션 생명 주기와 동일하게 사용 가능
▶ getProperty
▷ 데이터 값을 설정 할 때 사용
// <jsp:setProperty name="빈 이름" property="속성 이름" value="속성(데이터) 값"/>
<jsp:setProperty name="student" property="name" value="홍길동"/>
▶ setProperty
▷ 데이터 값을 가져올 때 사용
// <jsp:getProperty name="빈 이름" property="속성 이름" />
<jsp:getProperty name="student" property="name" />
▶ 실습
▷ 자바 빈 생성 : student.java
// student.java
package com.javalec.ex;
public class Student {
private String name;
private int age;
private int grade;
private int studentNum;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public int getStudentNum() {
return studentNum;
}
public void setStudentNum(int studentNum) {
this.studentNum = studentNum;
}
}
▷ jsp에서 액션 태그 주기 : beanEx.jsp
// beanEx.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<jsp:useBean id="student" class="com.javalec.ex.Student" scope="page" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<jsp:setProperty name="student" property="name" value="백씨"/>
<jsp:setProperty name="student" property="age" value="13"/>
<jsp:setProperty name="student" property="grade" value="6"/>
<jsp:setProperty name="student" property="studentNum" value="7"/>
이름 : <jsp:getProperty name="student" property="name" /><br />
나이 : <jsp:getProperty name="student" property="age" /><br />
학년 : <jsp:getProperty name="student" property="grade" /><br />
번호 : <jsp:getProperty name="student" property="studentNum" /><br />
</body>
</html>