5월 ~ 7월) 웹/jsp
57Day - useBean_action & useBean_display & useBean_form/ StudentDTO &$ StudentDAO & jdbcDAO &$$ displayStudent & insertFormStudent &updateFormStudent & updateStudent& deleteStudent
첼로그
2023. 7. 3. 01:31
6/26 일 (57day)
webapp > action >useBean )
useBean_action .jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 회원정보를 전달받아 내장객체의 속성값으로 저장하고 [useBean_display.jsp] 문서로 포워드
이동하는 JSP 문서 - 클라이언트 요청에 대한 처리만 제공하는 JSP 문서 --%>
<%
//JSP 문서를 GET 방식으로 요청한 경우 - 비정상적인 요청
if(request.getMethod().equals("GET")) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
return;
}
//POST 방식으로 요청하여 전달된 값에 대한 캐릭터셋 변경
request.setCharacterEncoding("utf-8");
%>
<%-- useBean Tag : JSP 문서에 Java 객체(JavaBean)를 제공하기 위한 태그 --%>
<%-- 형식)<jsp:useBean id="식별지" class="JavaBean 클래스" scope="사용범위"/> --%>
<%-- => 내장객체에 저장된 속성값을 객체로 반환받아 제공하거나 속성값이 없는 경우 객체를 생성하여
내장객체의 속성값으로 저장하여 제공 --%>
<%-- id 속성 : useBean 태그로 제공되는 객체를 구분하기 위한 식별자를 속성값으로 설정 --%>
<%-- => 내장객체에 저장된 속성값에 대한 속성명으로 사용 --%>
<%-- class 속성 : useBean 태그로 제공되는 객체의 자료형을 속성값으로 설정 --%>
<%-- scope 속성 : useBean 태그로 제공되는 객체의 사용범위(Scope)를 속성값으로 설정 --%>
<%-- => page, request, session, application 중 하나를 속성값으로 설정 --%>
<%-- => scope 속성을 생략한 경우 [page] 속성값을 기본값으로 설정하여 사용 --%>
<jsp:useBean id="hewon" class="xyz.itwill.bean.Hewon" scope="request"/>
<%--
//useBean 태그와 동일한 명령 - 객체를 생성하여 내장객체의 속성값으로 저장하여 제공
Hewon hewon=new Hewon();
request.setAttribute("hewon", hewon);
--%>
<%-- setProperty Tag : useBean 태그로 제공된 객체의 필드값을 변경하기 위한 태그 --%>
<%-- => 객체의 필드에 대한 Setter 메소드를 호출하여 객체의 필드값 변경 --%>
<%-- 형식)<jsp:setProperty name="식별자" property="필드명" value="변경값"/> --%>
<%-- name 속성 : useBean 태그로 제공된 객체의 식별자(id 속성값)을 속성값으로 설정 --%>
<%-- property 속성 : 값을 변경할 필드명을 속성값으로 설정 --%>
<%-- => 필드명을 기반으로 작성된 Setter 메소드 자동 호출 - 필드명으로 작성된 Setter 메소드가 없는 경우 에러 발생 --%>
<%-- value 속성 : 필드에 저장될 변경값을 속성값으로 설정 --%>
<%-- <jsp:setProperty name="hewon" property="name" value="홍길동"/> --%>
<%-- hewon.setName("홍길동"); --%>
<%-- value 속성을 생략하면 JSP 문서 요청시 전달된 값을 반환받아 필드값 변경 --%>
<%-- => JSP 문서 요청시 전달된 값의 이름과 setProperty 태그의 property 속성값(객체 필드명)이
반드시 동일해야만 전달값을 반환받아 객체 필드값으로 변경 --%>
<%--
<jsp:setProperty name="hewon" property="name"/>
<jsp:setProperty name="hewon" property="phone"/>
<jsp:setProperty name="hewon" property="address"/>
--%>
<%-- setProperty 태그의 property 속성값을 [*]로 설정한 경우 모든 전달값을 반환받아 필드값 변경 --%>
<jsp:setProperty name="hewon" property="*"/>
<%--
hewon.setName(request.getParameter("name"));
hewon.setPhone(request.getParameter("phone"));
hewon.setAddress(request.getParameter("address"));
--%>
<jsp:forward page="useBean_display.jsp"/>
<%--
request.getRequestDispatcher("useBean_display.jsp").forward(request, response);
--%>
useBean_form .jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 사용자로부터 회원정보를 입력받기 위한 JSP 문서 --%>
<%-- => [회원등록] 태그를 클릭한 경우 [useBean_action.jsp] 문서를 요청하여 이동 - 입력값(회원정보) 전달 --%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP</title>
</head>
<body>
<h1>회원정보등록</h1>
<hr>
<form action="useBean_action.jsp" method="post">
<table>
<tr>
<td>이름</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>전화번호</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>주소</td>
<td><input type="text" name="address"></td>
</tr>
<tr>
<td colspan="2"><button type="submit">회원등록</button></td>
</tr>
</table>
</form>
</body>
</html>
useBean_display .jsp (응답하는 문서)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 내장객체에 저장된 속성값을 반환받아 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%
//내장객체에 저장된 속성값이 없는 경우 - 비정상적인 요청
if(request.getAttribute("hewon")==null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP</title>
</head>
<body>
<h1>회원정보확인</h1>
<hr>
<jsp:useBean id="hewon" class="xyz.itwill.bean.Hewon" scope="request"/>
<%--
//useBean 태그와 동일한 명령 - 내장객체에 저장된 속성값을 객체로 반환받아 제공
Hewon hewon=(Hewon)request.getAttribute("hewon");
--%>
<%-- getProperty Tag : useBean 태그로 제공된 객체의 필드값을 반환하기 위한 태그 --%>
<%-- => 객체의 필드에 대한 Getter 메소드를 호출하여 객체의 필드값 반환 --%>
<%-- 형식)<jsp:getProperty name="식별자" property="필드명"/> --%>
<%-- name 속성 : useBean 태그로 제공된 객체의 식별자(id 속성값)을 속성값으로 설정 --%>
<%-- property 속성 : 값을 변경할 필드명을 속성값으로 설정 --%>
<%-- => 필드명을 기반으로 작성된 Getter 메소드 자동 호출 - 필드명으로 작성된 Getter 메소드가 없는 경우 에러 발생 --%>
<p>이름 = <jsp:getProperty name="hewon" property="name"/></p>
<p>전화번호 = <jsp:getProperty name="hewon" property="phone"/></p>
<p>주소 = <jsp:getProperty name="hewon" property="address"/></p>
<%--
<p>이름 = <%=hewon.getName() %></p>
<p>전화번호 = <%=hewon.getPhone() %></p>
<p>주소 = <%=hewon.getAddress() %></p>
--%>
</body>
</html>
+ 있어야 하는것
webapp > WEB-INF >lib )
ojdbc11
webapp > META-INF )
context.xml
> src/ main/ java > xyz.itwill.dto )
StudentDTO (sql로 먼저 테이블만들기)
package xyz.itwill.dto;
//create table student (NO NUMBER(4), NAME VARCHAR2(50), PHONE VARCHAR2(20)
//, ADDRESS VARCHAR2(100), BIRTHDAY DATE);
/*
이름 널? 유형
-------- -------- -------------
NO NOT NULL NUMBER(4)
NAME VARCHAR2(50)
PHONE VARCHAR2(20)
ADDRESS VARCHAR2(100)
BIRTHDAY DATE
*/
//STUDENT 테이블의 학생정보를 저장하여 전달하기 위한 클래스
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;
}
}
> src/ main/ java > xyz.itwill.dao )
StudentDAO
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;
//STUDENT 테이블의 행(학생정보)에 대한 삽입,변경,삭제,검색 기능을 제공하는 클래스
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();
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 테이블에 저장된 학생정보를 검색하여 DTO 객체로 반환하는 메소드
public StudentDTO selectStudent(int no) {
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
StudentDTO studnet=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()) {
studnet=new StudentDTO();
studnet.setNo(rs.getInt("no"));
studnet.setName(rs.getString("name"));
studnet.setPhone(rs.getString("phone"));
studnet.setAddress(rs.getString("address"));
studnet.setBirthday(rs.getString("birthday"));
}
} catch (SQLException e) {
System.out.println("[에러]selectStudent() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt, rs);
}
return studnet;
}
//STUDENT 테이블에 저장된 모든 학생정보를 검색하여 List 객체로 반환하는 메소드
public List<StudentDTO> selectStudentList() {
Connection con=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
List<StudentDTO> studnetList=new ArrayList<>();
try {
con=getConnection();
String sql="select * from student order by no";
pstmt=con.prepareStatement(sql);
rs=pstmt.executeQuery();
while(rs.next()) {
StudentDTO studnet=new StudentDTO();
studnet.setNo(rs.getInt("no"));
studnet.setName(rs.getString("name"));
studnet.setPhone(rs.getString("phone"));
studnet.setAddress(rs.getString("address"));
studnet.setBirthday(rs.getString("birthday"));
studnetList.add(studnet);
}
} catch (SQLException e) {
System.out.println("[에러]selectStudentList() 메소드의 SQL 오류 = "+e.getMessage());
} finally {
close(con, pstmt, rs);
}
return studnetList;
}
}
jdbcDAO
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;
//JDBC 기능을 제공하는 DAO 클래스가 상속받아 사용하기 위해 작성된 부모클래스 - 추상클래스
// => WAS 프로그램에 의해 관리되는 DataSource 객체를 제공받아 필드에 저장 - 정적영역에 작성하여 한번만 실행
// => DataSource 객체로부터 Connection 객체를 제공받아 반환하는 메소드
// => 매개변수로 전달받은 JDBC 관련 객체를 제거하는 메소드
public abstract class JdbcDAO {//상속만을 목적으로 작성된 클래스
private static DataSource dataSource;
static {
try {
dataSource=(DataSource)new InitialContext().lookup("java:comp/env/jdbc/oracle");
} 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();
}
}
}
webapp > student)
※ 형식변경 있음 !! >> 걍 rename눌러서 .jsp확장자 변경하고, 내용만 바꿔주면됨.
insertFormStudent.html (jsp 로 변경>) insertFormStudent.jsp
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 사용자로부터 학생정보를 입력받기 위한 JSP 문서 --%>
<%-- => [학생추가] 태그를 클릭한 경우 [insertStudent.jsp] 문서를 요청하여 이동 - 입력값(학생정보) 전달 --%>
<%-- => [학생목록] 태그를 클릭한 경우 [displayStudent.jsp] 문서를 요청하여 이동 --%>
<%
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>
updateFormStudent.html (jsp 로 변경>) updateFormStudent.jsp
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 학생번호를 전달받아 STUDENT 테이블에 저장된 학생정보를 검색하여 입력태그의 초기값으로
출력하고 변경값을 입력받기 위한 JSP 문서 --%>
<%-- => [학생변경] 태그를 클릭한 경우 [updateStudent.jsp] 문서를 요청하여 이동 - 입력값(학생정보) 전달 --%>
<%-- => [학생목록] 태그를 클릭한 경우 [displayStudent.jsp] 문서를 요청하여 이동 --%>
<%
//전달값이 없는 경우 - 비정상적인 요청
if(request.getParameter("no")==null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
//전달값을 반환받아 변수에 저장
int no=Integer.parseInt(request.getParameter("no"));
//학생번호를 전달받아 STUDENT 테이블에 저장된 학생정보를 검색하여 DTO 객체로 반환하는 DAO 클래스의 메소드 호출
StudentDTO student=StudentDAO.getDAO().selectStudent(no);
//STUDENT 테이블에 저장된 학생정보를 검색하지 못한 경우 - 비정상적인 요청
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] 문서를 요청할 때 학생번호도 전달되도록 설정 --%>
<%-- => 학생번호는 변경하지 못하도록 hidden Type으로 전달하거나 입력태그의 초기값을
변경하지 못하도록 readonly 속성 사용 --%>
<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">
<%-- <%=student.getNo()%> --%>
<input type="text" name="no" value="<%=student.getNo() %>" readonly="readonly">
</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">
function submitCheck() {
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="updateStudent.jsp";
studentForm.submit();
}
</script>
</body>
</html>
displayStudent .html (실행) (jsp 로 변경>) displayStudent.jsp
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- STUDENT 테이블에 저장된 모든 학생정보를 검색하여 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%-- => [학생추가] 태그를 클릭한 경우 [insertFormStudent.jsp] 문서를 요청하여 이동 --%>
<%-- => 학생정보 출력태그에서 [변경] 태그를 클릭한 경우 [updateFormStudent.jsp] 문서를 요청하여 이동 - 학생번호 전달 --%>
<%-- => 학생정보 출력태그에서 [삭제] 태그를 클릭한 경우 [deleteStudent.jsp] 문서를 요청하여 이동 - 학생번호 전달 --%>
<%
//STUDENT 테이블에 저장된 모든 학생정보를 검색하여 List 객체로 반환하는 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>
<!-- 학생정보 출력-->
<% 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="removeConfirm(<%=student.getNo()%>);"></td>
<td width="50"><input type="button" value="변경" onclick="location.href='updateFormStudent.jsp?no=<%=student.getNo()%>';"></td>
</tr>
<% } %>
</table>
<script type="text/javascript">
function removeConfirm(no) {
if(confirm("학생정보를 정말로 삭제 하시겠습니까?")) {
location.href="deleteStudent.jsp?no="+no;
}
}
</script>
</body>
</html>
updateStudent.jsp (변경)
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@page import="xyz.itwill.dto.StudentDTO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 학생정보를 전달받아 STUDENT 테이블에 저장된 학생정보를 변경하고 [displayStudent.jsp] 문서를
요청할 수 있는 URL 주소를 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%
//JSP 문서를 GET 방식으로 요청한 경우 - 비정상적인 요청
if(request.getMethod().equals("GET")) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
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");
//DTO 클래스로 객체를 생성하여 전달값으로 필드값 변경
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");
%>
deleteStudent.jsp (삭제시)
<%@page import="xyz.itwill.dao.StudentDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%-- 학생번호를 전달받아 STUDENT 테이블에 저장된 학생정보를 삭제하고 [displayStudent.jsp] 문서를
요청할 수 있는 URL 주소를 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%
//전달값이 없는 경우 - 비정상적인 요청
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) {//삭제행이 있는 경우 - 정상적인 요청
response.sendRedirect("displayStudent.jsp");
} else {//삭제행이 없는 경우 - 비정상적인 요청
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}
%>