CH04_1 useBean 태그를 이용한 DB연동

1. 설치파일

1) mysql 5.7버전 설치
2) 하이디 SQL 설치


2. 데이터베이스 생성

1) 하이디SQL 실행 후 DB 생성
- 이름 - mydb,
- 조합 - utf8_general_ci


2) 테이블 생성
create table tblTeam(
num int primary key auto_increment,
name char(10) not null,
city char(10) not null,
age int default 0,
team char(10) not null
)


3. 이클립스와 MYSQL 데이터베이스 연동 확인

1) mysql-connector-java.jar 파일 추가(경로 확인)

2) src/main/java 폴더에 ch04 패키지에 TeamMgr.java 파일 생성

public class TeamMgr {	
	private DBConnectionMgr pool;		
	public TeamMgr(){
		try {
			pool = DBConnectionMgr.getInstance();
			// java.sql.Connection;
			 Connection con = pool.getConnection();
			 System.out.println("DB 연결 성공");
		} catch (Exception e) {
			System.err.println("DB 연결 실패");
			e.printStackTrace();			
		}
	}
	public static void main(String[] args) {
		TeamMgr mgr = new TeamMgr();
	}
}

==> 결과
DB 연결 성공

실습1
1) useBean먼저 생성
2) html 페이지 생성
3) jsp 페이지 생성


<TeamBean.java>

package ch04;
public class TeamBean {
	private int num;
	private String name;
	private String city;
	private int age;
	private String team;	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getTeam() {
		return team;
	}
	public void setTeam(String team) {
		this.team = team;	
}

<TeamMgr.java>

  • <DBConnectionMgr.java> 페이지 생성 후
// TeamMgr.java
package ch04;
import java.sql.Connection;
import java.sql.PreparedStatement;
// jsp에서 db연동되는 메서드를 선언하는 클래스 무조건 TeamMgr 클래스를 사용
public class TeamMgr {	
	private DBConnectionMgr pool;		
	public TeamMgr(){
		try {
			pool = DBConnectionMgr.getInstance();
			// java.sql.Connection;
			 Connection con = pool.getConnection();
			 System.out.println("DB 연결 성공");
		} catch (Exception e) {
			System.err.println("DB 연결 실패");
			e.printStackTrace();			
		}
	}	
     // 저장
	//public void insertTeam(S) 
	public void insertTeam(TeamBean bean) {
		//java.sql 사용
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;		
		try { //pool에서 Connection에서 빌려옴 -> 사용 -> 반납
			con = pool.getConnection(); // 빌려옴
			sql = "insert tblTeam(name,city,age,team) values(?,?,?,?)";
			pstmt = con.prepareStatement(sql);// 공식			
			// sql 문에 있는 ?값 세팅
			pstmt.setString(1, bean.getName());
			pstmt.setString(2, bean.getCity());
			pstmt.setInt(3, bean.getAge());
			pstmt.setString(4, bean.getTeam());			
			//sql문 실행
			pstmt.executeUpdate();				
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			//Connection 반납, pstmt는 close
			pool.freeConnection(con, pstmt);
		}		
	}
	public static void main(String[] args) {
		TeamMgr mgr = new TeamMgr();
	}
}

<teamInsert.html>

<!-- teamInset.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Team Mgr</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	function check() {
		f=document.frm;
		if(f.name.value==""){
			alert("이름 입력하세요.")
			//function 중간 종료
			f.name.focus();
			return;
		}
		if(f.city.value==""){
			alert("사는곳 입력하세요.")
			f.city.focus();
			return;
		}
		if(f.age.value==""){
			alert("나이 입력하세요.")
			f.age.focus();
			return;
		}
		if(f.team.value.length==0){
			alert("팀 입력하세요.")
			f.team.focus();
			return;
		}		
		f.submit();
	}	
	function check2() {
		document.frm.action= "teamInsertProc2.jsp";
		document.frm.submit();
	}
</script>
</head>
<body>
<div align="center">
<h1>Team Insert</h1>
<form name="frm" method="post" action="teamInsertProc.jsp">
<table border="1">
<tr>
	<td width="50" align="center">이름</td>
	<td width="150"><input name="name" value="홍길동"></td>
</tr>
<tr>
	<td align="center">사는곳</td>
	<td><input name="city" value="부산"></td>
</tr>
<tr>
	<td align="center">나이</td>
	<td ><input name="age" value="27"></td>
</tr>
<tr>
	<td align="center">팀명</td>
	<td><input name="team" value="산적"></td>
</tr>
<tr>
	<td align="center" colspan="2">
		<input type="button" value="SAVE" onclick="check()">
		<input type="button" value="SAVE2" onclick="check2()">
	</td>
</tr>
</table><p/>
<a href="teamList.jsp">LIST</a>
</form>
</div>
</body>
</html>

<style.css>

	BODY {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TD {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
SELECT {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
DIV {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
FORM {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TEXTAREA {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999 ; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; BACKGROUND-COLOR: white
}
INPUT {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; HEIGHT: 19px; BACKGROUND-COLOR: white
}
A:link {text-decoration:none;color:#696969}
A:hover{text-decoration:yes;color:#66CCFF}
A:visited {text-decoration:none;color:#330066}

<teamInsertProc.jsp>

<%@page import="ch04.TeamMgr"%>
<%@page import="ch04.TeamBean"%>
<%@ page contentType="text/html; charset=EUC-KR"%>
<%
	request.setCharacterEncoding("EUC-KR");
	TeamBean bean = new TeamBean();
	String name = request.getParameter("name");
	String city = request.getParameter("city");
	int age = Integer.parseInt(request.getParameter("age"));
	String team = request.getParameter("team");	
	bean.setName(name);
	bean.setCity(city);
	bean.setAge(age);
	bean.setTeam(team);	
	TeamMgr mgr = new TeamMgr();
	mgr.insertTeam(bean);	
	//저장 후에 teamList.jsp로 응답
	response.sendRedirect("teamList.jsp");
%>

<teamInsertProx2.jsp>

<!-- teamInsertProc2.jsp -->
<%@ page contentType="text/html; charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<jsp:useBean id="bean" class="ch04.TeamBean"/>
<jsp:setProperty property="*" name="bean"/>
<%
	mgr.insertTeam(bean);
	response.sendRedirect("teamList.jsp");
%>

==> 결과
데이터베이스에 데이터 저장 확인


실습2

  • db에서 모든 데이터 조회하여 jsp페이지에 출력하기

    <TeamMgr.java>
    public class TeamMgr {	
	private DBConnectionMgr pool;		
	public TeamMgr(){
		try {
			pool = DBConnectionMgr.getInstance();
			// java.sql.Connection;
			// Connection con = pool.getConnection();
			 //System.out.println("DB 연결 성공");
		} catch (Exception e) {
			System.err.println("DB 연결 실패");
			e.printStackTrace();			
		}
	}
//리스트
	public Vector<TeamBean> listTeam(){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<TeamBean> vlist = new Vector<TeamBean>();
		try {
			con = pool.getConnection();
			sql = "select * from tblTeam";
			pstmt = con.prepareStatement(sql);
			// ?가 없기 때문에 세팅값은 없음
			//select, insert, update, delete는 executeUpdate()를 사용
			// executeUpdate()결과값은 int로 받음
			// executeQuery()결과값은 rs로 바로 받음
			rs = pstmt.executeQuery(); 
			while(rs.next()) {
				TeamBean bean = new TeamBean();
				/*
				int num = rs.getInt("num");
				String name = rs.getString("name");
				String city = rs.getString("city");
				int age = rs.getInt("age");
				String team = rs.getString("team");
				*/				
				bean.setNum(rs.getInt("num"));
				bean.setName(rs.getString("name"));
				bean.setCity(rs.getString("city"));
				bean.setAge(rs.getInt("age"));
				bean.setTeam(rs.getString("team"));		
				vlist.addElement(bean);				
			}			
		} catch (Exception e) {
			// 예외가 생긴 모든 경로 추적하여 출력되는 기능
			e.printStackTrace();
		}finally {
			// con은 반납, pstmt, rs는 사용후에 close
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}

<teamList.jsp>

<!-- teamList.jsp -->
<%@page import="ch04.TeamBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"></jsp:useBean>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Team Mgr</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div align="center"><p/>
<h1>Team List</h1>
<table border="1">
	<tr>
		<th>번호</th>
		<th>이름</th>
		<th>사는곳</th>
		<th>나이</th>
		<th>팀명</th>
	</tr>
	<%
		Vector<TeamBean> vlist = mgr.listTeam();
		// 배열 및 Vector 및에는 무조건 for문이 있다.		
		for(int i=0; i<vlist.size(); i++){
			TeamBean bean = vlist.get(i);
			int num = bean.getNum();
	%>
	<tr align="center">
		<td><%=i+1 %></td>
		<td><%=bean.getName() %></td>
		<td><%=bean.getCity() %></td>
		<td><%=bean.getAge() %></td>
		<td><%=bean.getTeam() %></td>		
	</tr>	
	<%
		}//for end
	%>
</table><p>
<a href="teamInsert.html">INSERT</a>
</div>
</body>

==> 결과


실습3

  • 리스트 페이지에서 번호(링크) 클릭 시 한 사람에 대한 정보 출력하기


    ==> 결과

    과정
    <teamList.jsp> 페이지에서 a 태그 추가
<tr align="center">
		<td><a href="teamRead.jsp?num=<%=num%>"><%=i+1 %></a></td>
		<td><%=bean.getName() %></td>
		<td><%=bean.getCity() %></td>
		<td><%=bean.getAge() %></td>
		<td><%=bean.getTeam() %></td>
	</tr>

<TeamMgr.java>

//회원 한 명 정보 가져오기
	public TeamBean getTeam(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		TeamBean bean = new TeamBean();				
		try {
			con = pool.getConnection();
			sql = "select * from tblTeam where num=?";
			pstmt = con.prepareStatement(sql);			
			//sql문에 첫번째 ?에 매개변수로 받아온 num 값을 세팅
			pstmt.setInt(1, num);
			//sql문 실행하고 실행 결과를 rs에 저장
			rs = pstmt.executeQuery();			
			if(rs.next()) {
				bean.setNum(rs.getInt(1)); //가져온 data 컬럼 순서 번호
				bean.setName(rs.getString(2));
				bean.setCity(rs.getString(3));
				bean.setAge(rs.getInt(4));
				bean.setTeam(rs.getString("team"));
			}			
		} catch (Exception e) {
			// 예외가 생긴 모든 경로 추적하여 출력되는 기능
			e.printStackTrace();
		}finally {
			// con은 반납, pstmt, rs는 사용후에 close
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}	

<teamRead.jsp>

<!-- teamRead.jsp -->
<%@page import="ch04.TeamBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"%>
<%--  == <%TeamBean mgr = new TeamBean(); %> --%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<%
	int num = Integer.parseInt(request.getParameter("num"));
	TeamBean bean = mgr.getTeam(num);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Team Mgr</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div align="center"><p/>
<h1>Team Read</h1>
<table border="1">
	<tr>
		<td>번호</td>
		<td><%=bean.getNum()%></td>
	</tr>
	<tr>
		<td>이름</td>
		<td><%=bean.getName()%></td>
	</tr>
	<tr>
		<td>사는곳</td>
		<td><%=bean.getCity()%></td>
	</tr>
	<tr>
		<td>나이</td>
		<td><%=bean.getAge()%></td>
	</tr>
	<tr>
		<td>팀명</td>
		<td><%=bean.getTeam()%></td>
	</tr>
</table><p>
<a href="teamList.jsp">LIST</a>&nbsp;&nbsp;
<a href="teamInsert.jsp">INSERT</a>&nbsp;&nbsp;
<a href="teamUpdate.jsp">UPDATE</a>&nbsp;&nbsp;
<a href="teamDelete.jsp">DELETE</a>&nbsp;&nbsp;
</div>
</body>

++추가 num값이 null이나 문자열 형식의 숫자가 아닌 값이 들어왔을 때 teamList.jsp 페이지로 페이지 이동


<teamRead.jsp> 추가 및 수정
- <% %> 태그 잘 확인하기!!!

<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<%
	int num = 0;
	String url = "teamList.jsp";
	// num 값이 요청이 없다면 teamList.jsp로 응답
	if(request.getParameter("num")==null){
		response.sendRedirect(url);
	}else if(!UtilMgr.isNumeric(request.getParameter("num"))){
		//숫자 형태의 문자열이 안들어옴 . 즉 "two" 와 같은 값이 저장됨
		response.sendRedirect(url);
	}else{
		//정상적으로 숫자가 잘 넘어옴
		num = Integer.parseInt(request.getParameter("num"));
		TeamBean bean = mgr.getTeam(num);
%>
</body>
<%
	}
%>

<UtilMgr.java> 페이지 추가

package ch04;
public class UtilMgr {
	//매개변수가 문자열 형식의 숫자이면 true, 문자열 형식의 숫자가 아니면 false
	public static boolean isNumeric(String s) {
		  try {
		      Integer.parseInt(s);
		      return true;
		  } catch(NumberFormatException e) {
		      return false;
		  }
	}
}

실습4

  • 데이터 정보 수정하기
    1) num 값으로 데이터 정보를 검색하고 페이지에 출력하기
    2) 출력된 데이터 수정 후 데이터 저장
    3) 수정된 데이터 페이지 출력하기


    ==> 결과



    1) <teamRead.jsp> 페이지 table 태그 맨아래 추가 작성
</table><p>
<a href="teamList.jsp">LIST</a>&nbsp;&nbsp;
<a href="teamInsert.jsp">INSERT</a>&nbsp;&nbsp;
<a href="teamUpdate.jsp?num=<%=num%>">UPDATE</a>&nbsp;&nbsp;
<a href="teamDelete.jsp?num=<%=num%>">DELETE</a>&nbsp;&nbsp;
</div>
</body>

2) <teamUpdate.jsp>

<!-- teamUpdate.jsp -->
<%@page import="ch04.TeamBean"%>
<%@page contentType="text/html; charset=EUC-KR"%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<%
		request.setCharacterEncoding("EUC-KR");
		int num = Integer.parseInt(request.getParameter("num"));
		TeamBean bean = mgr.getTeam(num);		
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Team Mgr</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div align="center">
<h1>Team Update</h1>
<form method="post" action="teamUpdateProc.jsp">
<table border="1">
<tr>
	<td width="50" align="center">번호</td>
	<td width="150">
		<input name="num" readonly value="<%=bean.getNum()%>">
	</td>
</tr>
<tr>
	<td  align="center">이름</td>
	<td>
		<input name="name" value="<%=bean.getName()%>">
	</td>
</tr>
<tr>
	<td align="center">사는곳</td>
	<td>
		<input name="city" value="<%=bean.getCity()%>">
	</td>
</tr>
<tr>
	<td align="center">나이</td>
	<td >
		<input name="age" value="<%=bean.getAge()%>">
	</td>
</tr>
<tr>
	<td align="center">팀명</td>
	<td>
		<input name="team" value="<%=bean.getTeam()%>">
	</td>
</tr>	
<tr>
	<td colspan="2" align="center">
		<input type="submit" value="UPDATE">
	</td>
</tr>
</table><p/>
</form>
<a href="teamRead.jsp?num=<%=num%>">READ</a>
</div>
</body>
</html>

3) <teamUpdateProc.jsp>

<%@ page contentType="text/html; charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<jsp:useBean id="bean" class="ch04.TeamBean"/>
<jsp:setProperty property="*" name="bean"/>
<%
	boolean result = mgr.updateTeam(bean);	
	String msg = "수정 실패";
	String url = "teamList.jsp";	
	if(result){
		msg = "수정 성공!!";
		url = "teamRead.jsp?num=" + bean.getNum();
	}
%>
<script>
alert("<%=msg%>");
location.href = "<%=url%>";
</script>

실습5

  • db에 저장된 데이터 삭제하기


    ==>결과

    <teamRead.jsp> 아래쪽에 내용 추가
</table><p>
<a href="teamList.jsp">LIST</a>&nbsp;&nbsp;
<a href="teamInsert.jsp">INSERT</a>&nbsp;&nbsp;
<a href="teamUpdate.jsp?num=<%=num%>">UPDATE</a>&nbsp;&nbsp;
<a href="teamDelete.jsp?num=<%=num%>">DELETE</a>&nbsp;&nbsp;
</div>
</body>

<teamDelete.jsp>

<%@ page contentType="text/html; charset=EUC-KR"%>
<jsp:useBean id="mgr" class="ch04.TeamMgr"/>
<%request.setCharacterEncoding("EUC-KR");
	int num = 0;
	if(request.getParameter("num")==null){
		response.sendRedirect("teamList.jsp");
	}
	num = Integer.parseInt(request.getParameter("num"));
	mgr.deleteTeam(num);
	response.sendRedirect("teamList.jsp");
%>

<TeamMgr.java>

//삭제
	public void deleteTeam(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;		
		try {
			con = pool.getConnection();
			sql = "delete from tblTeam where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}		
	}// deleteTeam end		

좋은 웹페이지 즐겨찾기