자바빈
빈(Bean)
- 재활용이 가능한 컴포넌트, 소프트웨어를 부품화, 재사용이 가능한 객체로써 대부분 데이터를 저장하는 역할
scope
- 객체가 사용될 수 있는 범위(Life Cycle)
- page : 현재 페이지까지 pageContext에 저장
- request : 다음 요청까지 HttpServletRequest에 저장, forward로 그다음까지 저장된다
- session : 브라우저를 떠나거나 session종료할 때까지 HttpSession에 저장
- application : WAS(Tomcat)을 다시 실행하기 전까지 ServletContext에 저장
액션태그 객체생성
-<jsp:useBean id=" " scope=" " typespec/>
- <jsp:useBean id="conn" class="app.Connection" /> = app.Connection conn = new app.Connection();
액션태그 객체 속성값 설정
- <jsp:setProperty name ="conn" property="timeout" value="33" /> = conn.setTimeout("33");
- <jsp:setProperty name ="conn" property="*" />
단, 한줄로써 처리가 가능하다
DTO 클래스
변수와, getter, setter 메소드로 구성되어져 있다
예제> 회원정보를 저장하는 빈
bean1.java
public class bean1 {
private String id; //아이디
private String password; //비밀번호
private String name; //이름
private int mclass; //회원구분 선택
private String tel1; //전화번호 1
private String tel2; //전화번호 2
private String tel3; //전화번호 3
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMclass() {
return mclass;
}
public void setMclass(int mclass) {
this.mclass = mclass;
}
public String getTel1() {
return tel1;
}
public void setTel1(String tel1) {
this.tel1 = tel1;
}
public String getTel2() {
return tel2;
}
public void setTel2(String tel2) {
this.tel2 = tel2;
}
public String getTel3() {
return tel3;
}
public void setTel3(String tel3) {
this.tel3 = tel3;
}
}
bean1.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("KSC5601"); %>
<jsp:useBean id="bean" class="contact.bean1" scope="page"/>
<jsp:setProperty property="*" name="bean"/>
<!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>
당신이 입력한 정보입니다.
<hr>
아이디 : <jsp:getProperty name="bean" property="id"/><br>
이름 : <jsp:getProperty name="bean" property="name"/><br>
회원구분 :
<% if(bean.getChoice() ==1)
out.print("일반회원");
else
out.print("교수님");
%>
<br>
전화번호 : <jsp:getProperty name="bean" property="phone1"/> -
<jsp:getProperty name="bean" property="phone2"/> -
<jsp:getProperty name="bean" property="phone3"/>
</body>
</html>
JDBC를 이용한 JSP와의 연동
JDBC를 이용한 데이터베이스 조작
1. JDBC 드라이버 로드(Driver Manager)
2. 데이터베이스와 연결(Connection)
3. SQL문 실행(Statement)
4. 데이터베이스와 연결을 끊는다(ResultSet - 결과값이 있다.)
1. JDBC 드라이버 로드(Driver Manager)
- import java.sql.*;
- Class.forName("oracle.jdbc.driver.OracleDriver"); <대/소문자 구분도 확실히!!>
2. 데이터베이스와 연결(Connection)
- Connection con = DriverManager.getConnection(url, uid, pwd);
url : JDBC형식 URL, uid : 사용자명, pwd : 패스워드
3. SQL문 실행(Statement)
- Statement stmt = con.createStatement();
4. 데이터베이스와 연결을 끊는다(ResultSet - 결과값이 있다.)
- executeQuery : select문과 같이 결과값이 여러 개의 레코드로 구해지는 경우
- executeUpdate : insert, update, delete문과 같은 내부적으로 테이블의 내용이 변경되고 결과값이 없는 경우 사용
- String str = "select * from member";
ResultSet rs = stmt.executeQuery(str);
데이터베이스 추가는 insert문을 사용한다.
insert문도 statement보단 preparestatement를 더 많이 사용한다
Preparestatement
form.html
<!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>
<form action="sqlinsert.jsp" method="post">
등록이름 : <input type="text" name="username"><br>
이메일 : <input type="text" name="email"><br>
<input type="submit" value="등록">
</form>
</body>
</html>
sqlinsert.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import ="java.sql.*" %>
<%
request.setCharacterEncoding("KSC5601");
Connection con = null;
PreparedStatement pstmt = null;
String url = "jdbc:oracle:thin:@localhost:1521:ORCL";
String uid = "scott";
String pwd = "tiger";
String sql = "insert into jdbc_test values(?, ?)";
int num=0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(url, uid, pwd);
//PrepareStatment 객체 생성
pstmt = con.prepareStatement(sql);
//PrepareStatement에 text값을 받아와서 setting
pstmt.setString(1, request.getParameter("username"));
pstmt.setString(2, request.getParameter("email"));
//executeUpadate는 pstmt에 넣어논 sql문을 실행하는 함수이다.
num = pstmt.executeUpdate();
} catch(Exception e) { }
%>
<!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>
<%
if(num == 1) {
%>
성공적으로 입력하셨습니다.
<br>
<a href="sqltest.jsp">결과보기</a>
<%
} else {
%>
입력에 실패하셨습니다.
<%
}
%>
</body>
</html>
DBCP(데이터베이스 커넥션 풀)
- DBCP 매니저가 어느 정도의 연결을 확보해 놓고 있다가 클라이언트 요청이 들어오면 연결해 주고,
클라이언트 작업이 끝나면 연결을 다시 Pool매니저에게 반환한다.
Servers -> server.xml -> 맨 밑 라인의 Context 안에 붙여넣기
<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver"
maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/oracle" password="tiger"
type="javax.sql.DataSource" url="jdbc:oracle:thin:@localhost:1521:ORCL" username="scott"/>
DataSource안에는 getConnection 함수가 있다
예제>DBCP 설정하는 방법
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("KSC5601"); %>
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.naming.*" %>
<%@ page import = "javax.sql.*" %>
<!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>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataSource ds = null;
String query = "select * from jdbc_test";
try {
//JNDI를 통한 커넥션 객체 구하기
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
con = ds.getConnection();
//쿼리문을 실행하기 위한 statement 객체 생성
//위에서 null포인터익셉션이 나타난다면 con을 주의깊게!
stmt = con.createStatement();
//4. sql문을 실행하여 결과 처리
rs = stmt.executeQuery(query);
while(rs.next()) {
%>
<!-- rs.getString으로 ResultSet에 있는 결과를 가져다 쓴다 -->
이름 :<%= rs.getString("username") %>
이메일 :<%= rs.getString("email") %>
<br>
<%
}
} catch(Exception e) { }
%>
</body>
</html>
자바빈 이용
- JDBC코드를 JAVA에 저장
JdbcDTO.java
public class JdbcDTO {
private String username;
private String email;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
JdbcDAO.java
public class JdbcDAO {
//공용변수로써 instance라는 자기 객체를 생성(싱글톤방식)
private static JdbcDAO instance = new JdbcDAO();
//Instance를 리턴함으로 DAO클래스를 한 페이지에서 계속 사용할 수 있게 해줬다.
public static JdbcDAO getInstance() {
return instance;
}
public Connection getConnection() throws Exception {
//InitialContext 이 함수 안에 있는 lookup을 사용해주기 위해서 Context를 쓴다.
Context ctx = new InitialContext();
//ctx.lookup("java:comp/env/경로명");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
Connection con = ds.getConnection();
return con;
}
public int insertJdbc(JdbcDTO jd) throws Exception {
int num=0;
Connection con = null;
PreparedStatement pstmt = null;
String sql = "insert into jdbc_text values(?, ?)";
try {
con.getClientInfo();
pstmt = con.prepareStatement(sql);
pstmt.setString(1, jd.getUsername());
pstmt.setString(2, jd.getEmail());
num = pstmt.executeUpdate();
pstmt.close();
con.close();
} catch(Exception e) {}
return num;
}
}
sqltest.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("KSC5601"); %>
<%@ page import = "java.sql.*" %>
<%@ page import = "javax.naming.*" %>
<%@ page import = "javax.sql.*" %>
<!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>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataSource ds = null;
String query = "select * from jdbc_test";
try {
//JNDI를 통한 커넥션 객체 구하기
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
con = ds.getConnection();
//쿼리문을 실행하기 위한 statement 객체 생성
//위에서 null포인터익셉션이 나타난다면 con을 주의깊게!
stmt = con.createStatement();
//4. sql문을 실행하여 결과 처리
rs = stmt.executeQuery(query);
while(rs.next()) {
%>
<!-- rs.getString으로 ResultSet에 있는 결과를 가져다 쓴다 -->
이름 :<%= rs.getString("username") %>
이메일 :<%= rs.getString("email") %>
<br />
<%
}
} catch(Exception e) { }
%>
</body>
</html>
1. jsp파일 안에 jdbc코드
-> 드라이버 로딩
-> connection
-> statement
-> resultset
2. jndi
-> 드라이버 로딩
-> datasource
-> connection
3. bean 이용
jdbc코드를 class에 보관
-> DAO, jdbc코드에 관련한 메소드들의 집합
JdbcDAO.java
public class JdbcDAO {
//공용변수로써 instance라는 자기 객체를 생성(싱글톤방식)
private static JdbcDAO instance = new JdbcDAO();
//Instance를 리턴함으로 DAO클래스를 한 페이지에서 계속 사용할 수 있게 해줬다.
public static JdbcDAO getInstance() {
return instance;
}
public Connection getConnection() throws Exception {
//InitialContext 이 함수 안에 있는 lookup을 사용해주기 위해서 Context를 쓴다.
Context ctx = new InitialContext();
//ctx.lookup("java:comp/env/경로명");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
//DataSource에 있는 getConnection을 갖게 됨
Connection con = ds.getConnection();
return con;
}
public int insertJdbc(JdbcDTO jd) throws Exception {
int num=0;
//커넥션 메소드 설정
Connection con = null;
//preparedStatement 메소드 설정
PreparedStatement pstmt = null;
//insert에 대한 sql문 설정
String sql = "insert into jdbc_text values(?, ?)";
//예외처리
try {
//커넥션에 위의 함수 getConnection을 넣어준다.
con = getConnection();
//prepare문에 insert 인자값을 넣어준다
pstmt = con.prepareStatement(sql);
pstmt.setString(1, jd.getUsername());
pstmt.setString(2, jd.getEmail());
//쿼리문을 실행하고 입력이 성공하면 1을 반환
num = pstmt.executeUpdate();
//메소드 닫기
pstmt.close();
con.close();
} catch(Exception e) {}
return num;
}
public ArrayList<JdbcDTO> selectList() throws Exception {
ArrayList<JdbcDTO> list = new ArrayList<JdbcDTO>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql = "select * from jdbc_test";
try {
//커넥션을 받는다
con = getConnection();
//statement생성
stmt = con.createStatement();
//statement의 결과값을 넣어준다
rs = stmt.executeQuery(sql);
while(rs.next()) {
JdbcDTO jd = new JdbcDTO();
//결과값을 DTO.java에 다시 설정
jd.setUsername(rs.getString("username"));
jd.setEmail(rs.getString("email"));
//설정한 값을 arraylist에 추가
list.add(jd);
}
} catch(Exception e) {
System.out.println(e.getMessage());
}
rs.close();
stmt.close();
con.close();
return list;
}
}
sqlinsert.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import ="java.sql.*" %>
<%@ page import="sql_first.*" %>
<% request.setCharacterEncoding("euc-kr"); %>
<!-- -->
<jsp:useBean id="jd" class="sql_first.JdbcDTO"/>
<!-- set메소드만 호출해주는 함수 setProperty -->
<jsp:setProperty property="*" name="jd"/>
<%
int num=0;
JdbcDAO dao = JdbcDAO.getInstance();
num = dao.insertJdbc(jd);
%>
<!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>
<%
if(num == 1) {
%>
성공적으로 입력하셨습니다.
<br />
<a href="sqltest.jsp">결과보기</a>
<%
} else {
%>
입력에 실패하셨습니다.
<%
}
%>
</body>
</html>
sqltest.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="sql_first.*" %>
<%@ page import ="java.sql.*" %>
<%@ page import="java.util.*" %>
<%@ page import ="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<jsp:useBean id="jd" class="sql_first.JdbcDTO"/>
<%
request.setCharacterEncoding("euc-kr");
ArrayList<JdbcDTO> list;
JdbcDAO dao = JdbcDAO.getInstance();
list = dao.selectList();
%>
<!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>
<table width=400 border=1 cellpadding="0" cellspacing="0">
<tr>
<th>이름</th>
<th>이메일</th>
</tr>
<%
for(int i=0; i<list.size(); i++) {
JdbcDTO jd2 = list.get(i);
String username = jd2.getUsername();
String email = jd2.getEmail();
%>
<tr>
<td><%= username %></td>
<td><%= email %></td>
</tr>
<% } %>
</table>
</body>
</html>
'Study > JSP' 카테고리의 다른 글
[jsp] 게시판 (0) | 2019.05.20 |
---|---|
[jsp] 회원가입, 로그인, 메인, 회원수정, 회원삭제, 자바빈 실습 (0) | 2019.05.20 |
[jsp] request, response, <jsp:forward>, <jsp:param>, 쿠키 실습 (0) | 2019.05.17 |
[jsp] request, response, <jsp:forward>, <jsp:param>, 쿠키 (0) | 2019.05.16 |
[jsp] 기초 실습 (0) | 2019.05.16 |