<TeamMgr.java>
기존의 TeamMgr.java 에서 삭제 메소드 밑에 아래의 코드 붙이기
// 입력된 팀이름 리스트
public Vector<String> teamList(){
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
Vector<String> vlist = new Vector<String>();
try {
con = pool.getConnection();
sql = "select distinct team from tblTeam";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
vlist.addElement(rs.getString(1));
}
//System.out.println(vlist.size());
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vlist;
}
<teamInsert.jsp>
<!-- ch09/teamInsert.jsp -->
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="mgr" class="ch09.TeamMgr"/>
<%
Vector<String> vlist = mgr.teamList();
%>
<html>
<head>
<meta charset="UTF-8">
<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("이름 입력하세요");
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==""){
alert("팀 입력하세요");
f.team.focus();
return; // 함수 빠져나옴
}
f.submit(); // 제출
}
function check2() {
document.frm.action = "teamInsertProc2.jsp";
document.frm.submit();
}
function selectTeam(){
// select의 name을 id로 변경
teamselect = document.getElementById("teamselect");
team = teamselect.options[teamselect.selectedIndex].value;
//alert(team);
document.frm.team.value = team;
}
</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" size="10">
<select id="teamselect" onchange="selectTeam()">
<%for(int i=0;i<vlist.size();i++){%>
<option value="<%=vlist.get(i)%>"><%=vlist.get(i)%></option>
<% }%>
</select>
</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>
</form><p>
<a href="teamList.jsp">LIST</a>
</div>
</body>
</html>
<결과>
<2번째 방법>
function selectTeam1(team){
document.frm.team.value = team;
}
<select id="teamselect" onchange="selectTeam1(this.value)">
<%for(int i=0;i<vlist.size();i++){%>
<option value="<%=vlist.get(i)%>"><%=vlist.get(i)%></option>
<% }%>
</select>
위 함수와 태그를 넣고 실행해도 같은 결과를 볼 수 있음.
1.JAVA
- DBConnectionMgr.java
- TeamBean.java
- TeamMgr.java
- MyUtil.java
2.JSP & html & css
- teamInsert.jsp(html) : 저장양식
- teamInsertProc.jsp : 저장처리
- teamList.jsp : 팀리스트
- teamRead.jsp : 한개의 team 정보
- teamDelete.jsp : 삭제
- teamUpdate.jsp : 수정양식
- teamUpdateProc.jsp : 수정처리
- style.css
page 사용시 데이터가 고정
session 사용시 새로운 데이터가 계속 갱신됨
<ScopeBean.java>
package ch09;
public class ScopeBean {
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
<scopeBean.jsp>
<!-- ch09/scopeBean.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<jsp:useBean id="pBean" class="ch09.ScopeBean" scope="page"/>
<jsp:useBean id="sBean" class="ch09.ScopeBean" scope="session"/>
<!--
scope 가 session 이면 id가 동일한 객체가 있는지 없는지 검색
-> 없으면 새롭게 생성
-> 하지만 있으면 그 객체를 재사용
-> 그러나 세션이 종료 또는 제거가 되면 안에있는 객체도 같이 없어짐.
-> scope="session" 밑에 코드가 많이 사용
-->
<% session.setAttribute("sBean",sBean); %>
<jsp:setProperty property="num" name="pBean"
value="<%=pBean.getNum()+10%>"/>
<jsp:setProperty property="num" name="sBean"
value="<%=sBean.getNum()+10%>"/>
<h1>Scope Bean</h1>
pBean num 값 : <jsp:getProperty property="num" name="pBean"/>
<br>
sBean num 값 : <jsp:getProperty property="num" name="sBean"/>
<br>
<a href="scopeBean2.jsp">세션종료</a>
<scopeBean2.jsp>
<!-- ch09/scopeBean2.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
// 세션에 특정한 값만 제거
session.removeAttribute("sBean");
// 세션 전체를 제거, 무효화, 초기화
session.invalidate();
response.sendRedirect("scopeBean.jsp");
%>
<결과>
<cookCokkie.jsp>
<!-- ch12/cookCookie.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String cookieName = "myCookie";
// 쿠키를 생성
Cookie cookie = new Cookie(cookieName,"Apple");
cookie.setMaxAge(60); // 1분
// 쿠키의 값을 변경
cookie.setValue("Melon");
// 쿠키 생성은 JSP 에서 했지만 Client 에게 전송
response.addCookie(cookie);
%>
쿠키를 만들었습니다.<br>
쿠키 내용은 <a href="tasteCookie.jsp">여기로!!</a>
<tasteCookie.jsp>
<!-- tasteCookie.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
// 응답된 쿠키의 정보는 request에 저장
Cookie []cookies = request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
%>
Cokkie Name : <%=cookies[i].getName() %><br>
Cokkie Value : <%=cookies[i].getValue() %><br>
<%
}
}
%>
<결과>
<login.jsp>
<!-- ch12/login.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String id = (String)session.getAttribute("idKey");
if(id!=null){
// 로그인 상태
%>
<script>
alert("로그인 되어었습니다.");
location.href="loginOK.jsp";
</script>
<%}%>
<!DOCTYPE html>
<html>
<head>
<title>Simple LogIn</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#996600" topmargin="100">
<h2 align="center">Session 로그인</h2>
<table width="75%" border="1" align="center" bordercolor="#660000" bgcolor="#FFFF99">
<tr bordercolor="#FFFF99">
<td height="190" colspan="7">
<form method="post" action="loginProc.jsp">
<table width="50%" border="1" align="center" cellspacing="0" cellpadding="0">
<tr bordercolor="#FFFF66">
<td colspan="2"><div align="center">Log in</div></td>
</tr>
<tr >
<td width="47%"><div align="center">ID</div></td>
<td width="53%"><div align="center"><input name="id"></div></td>
</tr>
<tr>
<td><div align="center">PWD</div></td>
<td><div align="center"><input name="pwd"></div></td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<input type="submit" value="login">
<input type="reset" value="reset">
</div>
</td>
</tr>
</table>
</form></td>
</tr>
</table>
</body>
</html>
<loginProc.jsp>
<!-- ch12/loginProc.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
// DB에 왔다 갔다 가정하고~
boolean result = true;
String msg = "로그인 실패 하였습니다.";
String url = "login.jsp";
if(result){
msg = "로그인 되었습니다.";
url = "loginOK.jsp";
session.setAttribute("idKey", id);
}
%>
<script>
alert("<%=msg%>");
location.href = "<%=url%>";
</script>
<loginOK.jsp>
<!-- ch12/loginOK.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
String id = (String)session.getAttribute("idKey");
if(id==null){
response.sendRedirect("login.jsp");
return; // _jspService 메소드 중간
}
%>
<!DOCTYPE html>
<html>
<head>
<title>Simple LogIn</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#996600" topmargin="100">
<table width="75%" border="1" align="center" cellpadding="1" cellspacing="1" bordercolor="#660000" bgcolor="#FFFF99">
<tr bordercolor="#FFFF99">
<td height="190" colspan="7">
<table width="50%" border="1" align="center" cellspacing="0" cellpadding="0">
<tr bordercolor="#FFFF66">
<td colspan="2"><div align="center">Log On Page</div></td>
</tr>
<tr >
<td><div align="center">
<strong><%=id%></strong>
님이 로그인 하셨습니다.
</div></td>
<td><div align="center">
<a href="logout.jsp"><strong>LOG OUT</strong></a>
</div></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
<logout.jsp>
<!-- ch12/logout.jsp -->
<%@page contentType="text/html; charset=UTF-8"%>
<%
session.invalidate();
response.sendRedirect("login.jsp");
%>
<결과>
GuestBook 구현
- guestbook : 패키지 및 폴더 생성
- table.sql -> 테이블 생성 3개
- JoinBean.java, GuestBookBean.java, CommentBean.java
<table.sql>
create table tblJoin(
id char(20) primary key,
pwd char(20) not null,
name char(20) not null,
email char(30),
hp char(40),
grade char(2) default '0'
);
create table tblGuestBook(
num int primary key auto_increment,
id char(20) not null,
contents text,
ip char(15) not null,
regdate date,
regtime datetime,
secret char(2) default '0'
);
create table tblComment(
cnum int primary key auto_increment,
num int not null,
cid char(20) not null,
comment text,
cip char(15) not null,
cregDate date
);
webapp -> guestbook 폴더 생성후 tabkle.sql 파일 넣기
mysql 파일 클릭 후 위의 화면처럼 따라하기
기존 5.1 파일이 있을 경우 add jar 클릭 후 8.0 파일 추가후 5.1 파일 remove 하기
url, name 수정 후 ok 버튼 누르기
테스트하기 눌러서 정상적으로 동작하면 -> finish 눌러 추가하기
오른쪽 마우스 클릭 후 excute all 누르기
mydb2에 테이블이 생성된것을 알 수 있음.
패키지 생성 후 위의 java 파일 생성
heidsql에 데이터 넣기
이후에 코드를 작성
<CommentBean.java>
package guestbook;
public class CommentBean {
private int num;
private int cnum;
private String cid;
private String comment;
private String cip;
private String cregDate;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getCnum() {
return cnum;
}
public void setCnum(int cnum) {
this.cnum = cnum;
}
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getCip() {
return cip;
}
public void setCip(String cip) {
this.cip = cip;
}
public String getCregDate() {
return cregDate;
}
public void setCregDate(String cregDate) {
this.cregDate = cregDate;
}
}
<GuestVookBean.java>
package guestbook;
public class GuestBookBean {
private int num;
private String id;
private String contents;
private String ip;
private String regdate;
private String regtime;
private String secret;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getRegtime() {
return regtime;
}
public void setRegtime(String regtime) {
this.regtime = regtime;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
<JoinBean.java>
package guestbook;
public class JoinBean {
private String id;
private String pwd;
private String name;
private String email;
private String hp;
private String grade;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getHp() {
return hp;
}
public void setHp(String hp) {
this.hp = hp;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
<GuestBookMgr.java>
package guestbook;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;
public class GuestBookMgr {
private DBConnectionMgr pool;
private final SimpleDateFormat SDF_DATE = new SimpleDateFormat("yyyy'년' M'월' d'일' (E)");
private final SimpleDateFormat SDF_TIME = new SimpleDateFormat("H:mm:ss");
public GuestBookMgr() {
pool = DBConnectionMgr.getInstance();
}
// Join Login
// select id from tblJoin where id = ? and pwd = ?
public boolean loginJoin(String id, String pwd) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
boolean flag = false;
try {
con = pool.getConnection();
sql = "select id from tblJoin where id = ? and pwd = ?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
flag = rs.next();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
return flag;
}
// Join Informantion
// select *from tblJoin where id = ?
public JoinBean getJoin(String id) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
JoinBean bean = new JoinBean();
try {
con = pool.getConnection();
sql = "select *from tblJoin where id = ?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
// where 절 이하에 조건이 pk 로 선언된 컬럼일때 if문으로 사용.
if (rs.next()) {
bean.setId(rs.getString(1));
bean.setPwd(rs.getString(2));
bean.setName(rs.getString(3));
bean.setEmail(rs.getString(4));
bean.setHp(rs.getString(5));
bean.setGrade(rs.getString(6));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return bean;
}
// GuestBook List
public Vector<GuestBookBean> listGuestBook(String id, String grade){
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
Vector<GuestBookBean> vlist = new Vector<GuestBookBean>();
try {
con = pool.getConnection();
if(grade.equals("1")) { // 관리자
sql = "select *from tblGuestBook order by num desc";
pstmt = con.prepareStatement(sql);
}else if(grade.equals("0")) {
sql = "select *from tblGuestBook "
+ "where id=? or secret = '0' order by num desc";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
}
rs = pstmt.executeQuery();
while(rs.next()) {
GuestBookBean bean = new GuestBookBean();
bean.setNum(rs.getInt("num"));
bean.setId(rs.getString("id"));
bean.setContents(rs.getString("contents"));
bean.setIp(rs.getString("ip"));
String tempDate = SDF_DATE.format(rs.getDate("regDate"));
bean.setRegdate(tempDate);
String tempTime = SDF_TIME.format(rs.getTime("regTime"));
bean.setRegdate(tempTime);
bean.setSecret(rs.getString("secret"));
vlist.addElement(bean);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return vlist;
}
// GuestBook Get
public GuestBookBean getGuestBook(int num) {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = null;
GuestBookBean bean = new GuestBookBean();
try {
con = pool.getConnection();
sql = "select *from tblGuestBook where num = ?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, num);
rs = pstmt.executeQuery();
if(rs.next()) {
bean.setNum(rs.getInt("num"));
bean.setId(rs.getString("id"));
bean.setContents(rs.getString("contents"));
bean.setIp(rs.getString("ip"));
String tempDate = SDF_DATE.format(rs.getDate("regDate"));
bean.setRegdate(tempDate);
String tempTime = SDF_TIME.format(rs.getTime("regTime"));
bean.setRegdate(tempTime);
bean.setSecret(rs.getString("secret"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt, rs);
}
return bean;
}
// GuestBook Insert
// sql = "insert tblGuestBook(id,contents,ip,regdate,regtime,secret)"
// values(?,?,?,now(),now(),?)";
public void insertGuestBook(GuestBookBean bean) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
try {
con = pool.getConnection();
sql = "insert tblGuestBook(id,contents,ip,regdate,regtime,secret)"
+"values(?,?,?,now(),now(),?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, bean.getId());
pstmt.setString(2, bean.getContents());
pstmt.setString(3, bean.getIp());
pstmt.setString(4, bean.getSecret());
pstmt.executeUpdate();// SQL로 실행
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
}
// GuestBook Update
// sql = "update tblGuestBook set contents=?,ip=?,secret=? "
// "where num=?";
public void updateGuestBook(GuestBookBean bean) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
try {
con = pool.getConnection();
sql = "update tblGuestBook set contents=?,ip=?,secret=? where num=?\"";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, bean.getContents());
pstmt.setString(2, bean.getIp());
pstmt.setString(3, bean.getSecret());
pstmt.setInt(4, bean.getNum());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
}
// GuestBook Delete
// sql = "delete from tblGuestBook where num=?";
public void deleteGuestBook(int num) {
Connection con = null;
PreparedStatement pstmt = null;
String sql = null;
try {
con = pool.getConnection();
sql = "delete from tblGuestBook where num=?";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.freeConnection(con, pstmt);
}
}
}
webapp -> guestbook -> 위 파일 생성
<login.jsp>
<!-- guestbook/login.jsp -->
<%@page contentType="text/html;charset=UTF-8"%>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<%
String id = (String)session.getAttribute("idKey");
String url = request.getParameter("url");
%>
<title>로그인</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<body bgcolor="#996600">
<br><br>
<div align="center">
<%
if(id!=null){
%>
<b><%=login.getName()%></b>님 환영합니다.<br>
<a href="showGuestBook.jsp" >방명록 </a>
<a href="logout.jsp" >로그아웃</a>
<%
}else{
%>
<h2>GuestBook 로그인</h2>
<form method="post" action="loginProc.jsp">
<table border="1">
<tr>
<td>id</td>
<td> <input name="id" value="aaa">
</td>
</tr>
<tr>
<td>pwd</td>
<td><input name="pwd" value="1234"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="hidden" name="url" value="<%=url%>">
<input type="submit" value="로그인">
</td>
</tr>
</table>
</form>
<%}%>
</div>
</body>
<loginProc.jsp>
<!-- guestbook/loginProc.jsp -->
<%@page contentType="text/html;charset=UTF-8"%>
<jsp:useBean id="mgr" class="guestbook.GuestBookMgr"/>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<!-- login.jsp 요청한 id, pwd 저장 -->
<jsp:setProperty property="*" name="login"/>
<%
String url = "login.jsp";
if(request.getParameter("url")!=null&&
!request.getParameter("url").equals("null")){
url = request.getParameter("url");
}
boolean result = mgr.loginJoin(login.getId(), login.getPwd());
//out.print(result);
String msg = "로그인 실패";
if(result){
msg = "로그인 성공";
login = mgr.getJoin(login.getId());
session.setAttribute("idKey", login.getId());
session.setAttribute("login", login);
}
%>
<script>
alert("<%=msg%>");
location.href = "<%=url%>";
</script>
<logout.jsp>
<!-- guestbook/logout.jsp -->
<%@page contentType="text/html;charset=UTF-8"%>
<%
session.invalidate();
%>
<script>
alert('로그아웃 되었습니다.');
location.href="login.jsp";
</script>
<임시결과>