<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/oracle" auth="Container" type="javax.sql.DataSource"
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe" username="scott" password="tiger"
initialSize="10" maxIdle="10" maxTotal="15"/>
</Context>
package xyz.itwill.dto;
//CREATE TABLE STUDENT(NO NUMBER(4) PRIMARY KEY,NAME VARCHAR2(50),PHONE VARCHAR2(50)
// ,ADDRESS VARCHAR2(100),BIRTHDAY DATE);
/*
이름 널? 유형
-------- -------- -------------
NO NOT NULL NUMBER(4)
NAME VARCHAR2(50)
PHONE VARCHAR2(20)
ADDRESS VARCHAR2(100)
BIRTHDAY DATE
*/
public class StudentDTO {
private int no;
private String name;
private String phone;
private String address;
private String birthday;
public StudentDTO() {
// TODO Auto-generated constructor stub
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
package xyz.itwill.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public abstract class JdbcDAO {//추상클래스
private static DataSource dataSource;
static {
try {
dataSource=(DataSource)new InitialContext().lookup("java:comp/env/jdbc/oracle");
//WAS프로그램에 등록된 자원을 얻어와 DataSource 객체를 반환받아 저장(명시적 객체 형변환)
} catch (NamingException e) {
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public void close(Connection con) {
try {
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(Connection con, PreparedStatement pstmt) {
try {
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void close(Connection con, PreparedStatement pstmt, ResultSet rs) {
try {
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package xyz.itwill.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import xyz.itwill.dto.StudentDTO;
public class StudentDAO extends JdbcDAO {
private static StudentDAO _dao;//싱글톤 클래스
private StudentDAO() {
// TODO Auto-generated constructor stub
}
static {
_dao=new StudentDAO();
}
public static StudentDAO getDAO() {
return _dao;
}
//학생정보를 전달받아 STUDENT 테이블에 삽입하고 삽입행의 갯수를 반환하는 메소드
public int insertStudent(StudentDTO student) {
Connection con=null;
PreparedStatement pstmt=null;
int rows=0;
try {
con=getConnection();
//setXXX 메소드호출하여 InParameter에 java전달값 전달
String sql="insert into student values(?,?,?,?,?)";
pstmt=con.prepareStatement(sql);
pstmt.setInt(1, student.getNo());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getPhone());
pstmt.setString(4, student.getAddress());
pstmt.setString(5, student.getBirthday());
rows=pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("[에러]insertStudent() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt);
}
return rows;
}
//학생정보를 전달받아 STUDENT 테이블에 저장된 학생정보를 변경하고 변경행의 갯수를 반환하는 메소드
public int updateStudent(StudentDTO student) {
Connection con=null;
PreparedStatement pstmt=null;
int rows=0;
try {
con=getConnection();
String sql="update student set name=?,phone=?,address=?,birthday=? where no=?";
pstmt=con.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setString(2, student.getPhone());
pstmt.setString(3, student.getAddress());
pstmt.setString(4, student.getBirthday());
pstmt.setInt(5, student.getNo());
rows=pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("[에러]updateStudent() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt);
}
return rows;
}
//학생번호를 전달받아 STUDENT 테이블에 저장된 학생정보를 삭제하고 삭제행의 갯수를 반환하는 메소드
public int deleteStudent(int no) {
Connection con=null;
PreparedStatement pstmt=null;
int rows=0;
try {
con=getConnection();
String sql="delete from student where no=?";
pstmt=con.prepareStatement(sql);
pstmt.setInt(1, no);
rows=pstmt.executeUpdate();
} catch (SQLException e) {
System.out.println("[에러]deleteStudent() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt);
}
return rows;
}
//학생정보를 전달받아 STUDENT 테이블에 저장된 해당 학생번호의 학생정보를 검색하여 반환하는 메소드
public StudentDTO selectStudent(int no) {
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
StudentDTO student=null;
try {
con=getConnection();
String sql="select * from student where no=?";
pstmt=con.prepareStatement(sql);
pstmt.setInt(1, no);
rs=pstmt.executeQuery();
if(rs.next()) {
student=new StudentDTO();
//getXXX : ResultSet 커서가 위치한 처리행의 컬럼값을 반환하는 메소드
student.setNo(rs.getInt("no"));
student.setName(rs.getString("name"));
student.setPhone(rs.getString("phone"));
student.setAddress(rs.getString("address"));
student.setBirthday(rs.getString("birthday"));
}
} catch (SQLException e) {
System.out.println("[에러]selectStudent() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt, rs);
}
return student;
}
//STUDENT 테이블에 저장된 모든 학생정보를 검색하여 반환하는 메소드
public List<StudentDTO> selectStudentList() {
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
List<StudentDTO> studentList=new ArrayList<>();
try {
con=getConnection();
String sql="select * from student order by no";
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()) {
StudentDTO student=new StudentDTO();
student.setNo(rs.getInt("no"));
student.setName(rs.getString("name"));
student.setPhone(rs.getString("phone"));
student.setAddress(rs.getString("address"));
student.setBirthday(rs.getString("birthday"));
studentList.add(student);
}
} catch (SQLException e) {
System.out.println("[에러]selectStudentList() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt, rs);
}
return studentList;
}
}
STUDENT 테이블에 저장된 모든 학생정보를 검색하여 클라이언트에게 전달하는 JSP 문서

<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@page import="java.util.List"%>
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//STUDENT 테이블에 저장된 모든 학생정보를 검색하여 반환하는 DAO 클래스의 메소드를 호출하여
//검색결과를 반환받아 저장
List<StudentDTO> studentList=StudentDAO.getDAO().selectStudentList();
%>
<!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=UTF-8">
<title>JSP</title>
</head>
<body>
<h1 align="center">학생목록</h1>
<table align="center" cellspacing="0" cellpadding="1" width="800">
<tr align="right">
<td>
<input type="button" value="학생추가" onclick="location.href='insertFormStudent.jsp';">
</td>
</tr>
</table>
<table align="center" border="1" cellspacing="0" cellpadding="1" width="800">
<tr bgcolor="yellow">
<th width="100">학생번호</th>
<th width="100">이름</th>
<th width="150">전화번호</th>
<th width="250">주소</th>
<th width="100">생년월일</th>
<th width="50">삭제</th>
<th width="50">변경</th>
</tr>
<% if(studentList.isEmpty()) {//List 객체에 저장된 요소가 없는 경우 %>
<tr align="center">
<td colspan="7">검색된 학생정보가 없습니다.</td>
</tr>
<% } else {//List 객체에 저장된 요소가 있는 경우 %>
<%-- List 객체에 저장된 요소를 차례대로 제공받아 응답하도록 반복 처리 --%>
<%-- => 반복문에서는 요소(학생정보 - StudentDTO 객체)의 필드값을 반환받아 클라이언트에게 전달 --%>
<% for(StudentDTO student:studentList) { %>
<tr align="center">
<td width="100"><%=student.getNo() %></td>
<td width="100"><%=student.getName() %></td>
<td width="150"><%=student.getPhone() %></td>
<td width="250"><%=student.getAddress() %></td>
<td width="100"><%=student.getBirthday().substring(0, 10) %></td>
<td width="50"><input type="button" value="삭제"
onclick="location.href='deleteStudent.jsp?no=<%=student.getNo()%>';"></td>
<td width="50"><input type="button" value="변경"
onclick="location.href='updateFormStudent.jsp?no=<%=student.getNo()%>';"></td>
</tr>
<% } %>
<% } %>
</table>
</body>
</html>
사용자로부터 학생정보를 입력받기 위한 JSP 문서

<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String message=(String)session.getAttribute("message");
if(message==null) {
message="";
} else {
session.removeAttribute("message");
}
StudentDTO student=(StudentDTO)session.getAttribute("student");
if(student!=null) {
session.removeAttribute("student");
}
%>
<!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=UTF-8">
<title>JSP</title>
</head>
<body>
<h1 align="center">학생정보 입력</h1>
<hr>
<form name="studentForm">
<table align="center" border="1" cellpadding="1" cellspacing="0" width="300">
<tr height="40">
<th bgcolor="yellow" width="100">학생번호</th>
<td width="200" align="center">
<input type="text" name="no" <% if(student!=null) { %> value="<%=student.getNo()%>" <% } %>>
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">이름</th>
<td width="200" align="center">
<input type="text" name="name" <% if(student!=null) { %> value="<%=student.getName()%>" <% } %>>
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">전화번호</th>
<td width="200" align="center">
<input type="text" name="phone" <% if(student!=null) { %> value="<%=student.getPhone()%>" <% } %>>
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">주소</th>
<td width="200" align="center">
<input type="text" name="address" <% if(student!=null) { %> value="<%=student.getAddress()%>" <% } %>>
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">생년월일</th>
<td width="200" align="center">
<input type="text" name="birthday" <% if(student!=null) { %> value="<%=student.getBirthday()%>" <% } %>>
</td>
</tr>
<tr height="40">
<td width="200" colspan="2" align="center">
<input type="button" value="학생추가" onclick="submitCheck();">
<input type="reset" value="초기화">
<input type="button" value="학생목록" onclick="location.href='displayStudent.jsp';">
</td>
</tr>
</table>
</form>
<p align="center" style="color: red;"><%=message %></p>
<script type="text/javascript">
studentForm.no.focus();
function submitCheck() {
if(studentForm.no.value=="") {
alert("학생번호를 입력해 주세요.");
studentForm.no.focus();
return;
}
var noReg=/\d{4}/g;
if(!noReg.test(studentForm.no.value)) {
alert("학생번호는 정수 4자리로 입력해주세요.");
studentForm.no.focus();
return;
}
if(studentForm.name.value=="") {
alert("이름을 입력해 주세요.");
studentForm.name.focus();
return;
}
if(studentForm.phone.value=="") {
alert("전화번호을 입력해 주세요.");
studentForm.phone.focus();
return;
}
var phoneReg=/(01[016789])-\d{3,4}-\d{4}/g;
if(!phoneReg.test(studentForm.phone.value)) {
alert("전화번호를 형식에 맞게 입력해주세요.");
studentForm.phone.focus();
return;
}
if(studentForm.address.value=="") {
alert("주소을 입력해 주세요.");
studentForm.address.focus();
return;
}
if(studentForm.birthday.value=="") {
alert("생년월일을 입력해 주세요.");
studentForm.birthday.focus();
return;
}
var birthdayReg=/(18|19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])/g;
if(!birthdayReg.test(studentForm.birthday.value)) {
alert("생년월일을 형식에 맞게 입력해주세요.");
studentForm.birthday.focus();
return;
}
studentForm.method="POST";
studentForm.action="insertStudent.jsp";
studentForm.submit();
}
</script>
</body>
</html>
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//비정상적인 요청에 대한 응답처리
if(request.getMethod().equals("GET")) {
session.setAttribute("message", "비정상적인 방법으로 페이지를 요청 하였습니다.");
response.sendRedirect("insertFormStudent.jsp");//입력페이지의 URL 주소 전달
return;
}
//POST 방식으로 요청하여 전달된 값에 대한 캐릭터셋 변경
request.setCharacterEncoding("utf-8");
//전달값을 반환받아 저장
int no=Integer.parseInt(request.getParameter("no"));
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String address=request.getParameter("address");
String birthday=request.getParameter("birthday");
//StudentDTO 객체를 생성하고 전달값으로 객체의 필드값 변경 - DAO 클래스의 메소드 호출에 사용
StudentDTO student=new StudentDTO();
student.setNo(no);
student.setName(name);
student.setPhone(phone);
student.setAddress(address);
student.setBirthday(birthday);
//사용자로부터 입력되어 전달된 학생번호가 STUDENT 테이블에 저장된 기존 학생정보의 학생번호와
//중복될 경우 입력페이지(insertFormStudent.jsp)로 이동하기 위한 URL 주소 전달
//학생번호를 전달받아 STUDENT 테이블에 저장된 해당 학생번호의 학생정보를 검색하여 반환하는
//DAO 클래스의 메소드 호출
// => null 반환 : 학생정보 미검색 - 전달된 학생번호 미중복
// => StudentDTO 객체 반환 : 학생정보 검색 - 전달된 학생번호 중복
if(StudentDAO.getDAO().selectStudent(no)!=null) {//검색된 학생정보가 있는 경우
session.setAttribute("message", "이미 사용중인 학생번호를 입력 하였습니다. 다시 입력해 주세요.");
session.setAttribute("student", student);
response.sendRedirect("insertFormStudent.jsp");
return;
}
//학생정보를 전달받아 STUDENT 테이블에 삽입하는 DAO 클래스의 메소드 호출
StudentDAO.getDAO().insertStudent(student);
//학생목록 출력페이지의 URL 주소를 전달하여 응답 처리
response.sendRedirect("displayStudent.jsp");
%>
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//비정상적인 요청에 대한 응답 처리
if(request.getParameter("no")==null) {//전달값(학생번호)이 없는 경우
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//전달값을 반환받아 저장
int no=Integer.parseInt(request.getParameter("no"));
//학생번호를 전달받아 STUDENT 테이블에 저장된 해당 학생번호의 학생정보를 삭제하는 DAO 클래스의 메소드 호출
int rows=StudentDAO.getDAO().deleteStudent(no);
if(rows>0) {//삭제된 학생정보가 있는 경우 - 정상적인 요청
//클라이언트에게 URL 주소 전달
response.sendRedirect("displayStudent.jsp");
} else {//삭제된 학생정보가 없는 경우 - 비정상적인 요청
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
%>
학생목록 출력페이지(displayStudent.jsp)에서 전달받은 학생번호를 반환받아 STUDENT 테이블에 저장된 해당 학생번호의 학생정보를 검색하여 입력태그의 초기값으로 설정하고 사용자로부터 변경값을 입력받기 위한 JSP 문서

<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//비정상적인 요청에 대한 응답 처리
if(request.getParameter("no")==null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//전달값을 반환받아 저장
int no=Integer.parseInt(request.getParameter("no"));
//학생번호를 전달받아 STUDENT 테이블에 저장된 해당 학생번호의 학생정보를 검색하여 반환하는
//DAO 클래스의 메소드 호출
StudentDTO student=StudentDAO.getDAO().selectStudent(no);
if(student==null) {//검색된 학생정보가 없는 경우 - 비정상적인 요청
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
%>
<!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=UTF-8">
<title>JSP</title>
</head>
<body>
<h1 align="center">학생정보 변경</h1>
<hr>
<%-- 학생정보 변경페이지(updateStudent.jsp) 요청시 학생번호(식별자)를 전달해야 되지만
학생번호는 변경하지 못하도록 설정 --%>
<%-- => 입력태그의 readonly 속성을 사용하여 초기값을 변경하지 못하도록 설정 --%>
<%-- => 입력태그의 타입을 [hidden]으로 설정하여 초기값을 전달하도록 설정 --%>
<form name="studentForm">
<input type="hidden" name="no" value="<%=student.getNo()%>">
<table align="center" border="1" cellpadding="1" cellspacing="0" width="300">
<tr height="40">
<th bgcolor="yellow" width="100">학생번호</th>
<td width="200" align="center">
<%-- <input type="text" name="name" value="<%=student.getNo() %>" readonly="readonly"> --%>
<%=student.getNo()%>
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">이름</th>
<td width="200" align="center">
<input type="text" name="name" value="<%=student.getName() %>">
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">전화번호</th>
<td width="200" align="center">
<input type="text" name="phone" value="<%=student.getPhone() %>">
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">주소</th>
<td width="200" align="center">
<input type="text" name="address" value="<%=student.getAddress() %>">
</td>
</tr>
<tr height="40">
<th bgcolor="yellow" width="100">생년월일</th>
<td width="200" align="center">
<input type="text" name="birthday" value="<%=student.getBirthday().substring(0, 10) %>">
</td>
</tr>
<tr height="40">
<td width="200" colspan="2" align="center">
<input type="button" value="학생변경" onclick="submitCheck();">
<input type="reset" value="초기화">
<input type="button" value="학생목록" onclick="location.href='displayStudent.jsp';">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
studentForm.num.focus();
function submitCheck() {
if(studentForm.name.value=="") {
alert("이름을 입력해 주세요.");
studentForm.name.focus();
return;
}
if(studentForm.phone.value=="") {
alert("전화번호을 입력해 주세요.");
studentForm.phone.focus();
return;
}
if(studentForm.address.value=="") {
alert("주소을 입력해 주세요.");
studentForm.address.focus();
return;
}
if(studentForm.birthday.value=="") {
alert("생년월일을 입력해 주세요.");
studentForm.birthday.focus();
return;
}
studentForm.method="POST";
studentForm.action="updateStudent.jsp";
studentForm.submit();
}
</script>
</body>
</html>
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//비정상적인 요청에 대한 응답처리
if(request.getMethod().equals("GET")) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
//POST 방식으로 요청하여 전달된 값에 대한 캐릭터셋 변경
request.setCharacterEncoding("utf-8");
//전달값을 반환받아 저장
int no=Integer.parseInt(request.getParameter("no"));
String name=request.getParameter("name");
String phone=request.getParameter("phone");
String address=request.getParameter("address");
String birthday=request.getParameter("birthday");
//StudentDTO 객체를 생성하고 전달값을 이용하여 필드값 변경
StudentDTO student=new StudentDTO();
student.setNo(no);
student.setName(name);
student.setPhone(phone);
student.setAddress(address);
student.setBirthday(birthday);
//학생정보를 전달받아 STUDENT 테이블에 저장된 해당 학생정보를 변경하는 DAO 클래스의 메소드 호출
StudentDAO.getDAO().updateStudent(student);
//클라이언트에게 URL 주소 전달
response.sendRedirect("displayStudent.jsp");
%>