■ JSP 정리
□ jsp에서 자바코드 사용하기
<%! ~~ %> : 선언문. 주로 메소드 선언할 때, 혹은 멤버필드 정의할 때
<% ~~ %> : scriptlet, _jspService 메소드 안에 기록 (그래서 선언을 따로 한다. 메소드 안의 메소드는 X, 클래스는 가능(지역 중첩 클래스)
<%= ~ %> : 표현식, java내용을 html상에 나타낼때
□ jsp 지시어 : <%@ ~~ %>
1. page : 현재 클래스에 지정
- request : 서버에 요구하는 모든 값
- response : 서버가 지정해서 내려주는 값
2. include : Template page 만들기
3. taglib : 사용자정의태그 작성 -> jstl
□ scope (사용범위)
- page : 현재page에서, default
- request : 두개의 page에서 적용, forward, include 액션태그를 통해 이동할 때
- session : 브라우저에서 적용
- application : 서버에서 적용
□ jsp액션태그
- <jsp:useBean> : 객체선언
- 속성값에는 아래와 같은 것들이 있다.
- id : 객체명
- class : 실제 경로명
- scope : 사용범위
- <jsp:setProperty> : setter 메소드에 적용
- name : useBean으로 선언된 객체명
- value : setter 메소드에 들어갈 값, default는 parameter값을 넣을때 주로 사용
- property : setter메소드명, 전체 메소드는 *
- <jsp:include page="이동할페이지"/> : 갔다가 다시 돌아옴
- <jsp:forward page="이동할페이지"/> : 가서 안 옴, forward 이전 페이지에는 절대 출력문이 있으면 안 된다.
□ 내장객체
- jsp파일을 java파일로 변환할때 필요한 값을 미리 설정하여 사용할 수 있게 만들어 주는 객체
- page, request, response, session, application, config, out
□ session과 Cookie
- http통신은 한번만 통신을 한다. 연결성이 없다. 이러한 문제를 해결하기 위한 기술
- session : 서버에 값을 기록하여 관리
- Cookie : 서버에서 만들어서 클라이언트에 값을 기록하여 관리. 단점은 암호화를 시킬 수 없다.
□ DTO와 DAO
DTO : Data Transfer Object
- 테이블의 컬럼명과 동일한 private 멤버필드를 만든다
- 모든 멤버필드의 setter, getter메소드를 만든다
DAO : Data Access Object
- CRUD 작업하는 곳
■ 드라이버 연결 (JDBC)
package jdbc;
import java.sql.*;
public class Test01 {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("오라클 드라이버 검색 성공");
} catch(ClassNotFoundException e) {
System.err.println("오라클 드라이버 검색 실패");
}
Connection con = null;
try {
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "web01";
String pass = "web01";
con = DriverManager.getConnection(url, user, pass);
System.out.println("드라이버 연결 성공!");
} catch(SQLException e) {
System.err.println("드라이버 연결 실패!");
e.printStackTrace();
}
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = "update student set cname = ? where name = ?";
ps = con.prepareStatement(sql);
ps.setString(1, "abab");
ps.setString(2, "aaa");
int res = ps.executeUpdate();
if(res > 0) {
System.out.println("데이터 수정 성공!");
} else {
System.out.println("데이터 수정 실패!");
}
} catch(SQLException e) {
System.err.println("update중 오류 발생");
e.printStackTrace();
}
/*
* try { String sql = "select * from student";
* ps = con.prepareStatement(sql);
* rs = ps.executeQuery();
*
* System.out.println("id\tname\tcname");
* while(rs.next()) {
* String id =
* rs.getString("id");
* String name = rs.getString("name");
* String cname = rs.getString("cname");
* System.out.println(id + "\t" + name + "\t" + cname);
* }
* } catch(SQLException e) {
* System.err.println("select 실행 중 오류 발생");
* e.printStackTrace();
* }
*/
/*
* try { String sql = "insert into student values(?, ?, ?)"; // 동적쿼리의 특징
* ps = con.prepareStatement(sql); // 쿼리문 전송
*
* ps.setString(1, "aaa"); // ? 순서에 해당 data값 넣기
* ps.setString(2, "aaa");
* ps.setString(3, "aaa");
*
* int res = ps.executeUpdate(); // data를 모두 넣었다면 실행
*
* if(res > 0) {
* System.out.println("aaa 데이터 넣기 성공!");
* } else {
* System.out.println("aaa 데이터 넣기 실패");
* }
* } catch(SQLException e) {
* System.err.println("insert 중 오류 발생!"); e.printStackTrace();
* }
*/
}
}
■ testJSP
□ student 패키지
* StudentDTO.Java
package student;
public class StudentDTO {
private String id;
private String name;
private String cname;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
}
* StudentDAO.java
package student;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String url, user, pass;
/*
* 생성자는 무조건 public 으로 자바의 접근제한자. 왜냐하면 장소가 다르기 때문이다.
* private : 클래스 내부에서만 접근
* default : 선언하지 않는다. 사실 package라고 쓰는 건데 겹치니까. 같은 package 안에서 접근 가능
* protected : default + 상속받은 클래스
* public 모두 접근이 가능하다.
*/
public StudentDAO() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
url = "jdbc:oracle:thin:@localhost:1521:xe";
user = "web01";
pass = "web01";
}
public int insertStudent(StudentDTO dto) throws SQLException{
try {
con = DriverManager.getConnection(url, user, pass);
String sql = "insert into student values(?, ?, ?)";
ps = con.prepareStatement(sql);
ps.setString(1, dto.getId());
ps.setString(2, dto.getName());
ps.setString(3, dto.getCname());
int res = ps.executeUpdate();
return res;
} finally { // 실행되는 스레드는 멀티스레드, 순서는 try가 끝난 직후부터 ps, con이라는 자원을 다른 스레드에서 닫는 것
if(ps != null) ps.close();
if(con != null) con.close();
}
}
public List<StudentDTO> listStudent() throws SQLException {
try {
con = DriverManager.getConnection(url, user, pass);
String sql = "select * from student";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
List<StudentDTO> list = new ArrayList<>();
while(rs.next()) {
StudentDTO dto = new StudentDTO();
dto.setId(rs.getString("id"));
dto.setName(rs.getString("name"));
dto.setCname(rs.getString("cname"));
list.add(dto);
}
return list;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(con != null) con.close();
}
}
public int deleteStudent(String id) throws SQLException {
try {
con = DriverManager.getConnection(url, user, pass);
String sql = "delete from student where id=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, id);
int res = ps.executeUpdate();
return res;
} finally {
if(ps != null) ps.close();
if(con != null) con.close();
}
}
public List<StudentDTO> findStudent(String cname) throws SQLException {
try {
con = DriverManager.getConnection(url, user, pass);
String sql = "select * from student where cname = ?";
ps = con.prepareStatement(sql);
ps.setString(1, cname);
rs = ps.executeQuery();
List<StudentDTO> list = makeList(rs);
return list;
} finally {
if(rs != null) rs.close();
if(ps != null) ps.close();
if(con != null) con.close();
}
}
protected List<StudentDTO> makeList(ResultSet rs) throws SQLException{
List<StudentDTO> list = new ArrayList<>();
while(rs.next()) {
StudentDTO dto = new StudentDTO();
dto.setId(rs.getString("id"));
dto.setName(rs.getString("name"));
dto.setCname(rs.getString("cname"));
list.add(dto);
}
return list;
}
}
□ jsp 페이지
* student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>학생관리</title>
</head>
<body>
<div align="center">
<hr color="green" width="300">
<h2> 학 생 등 록 페 이 지 </h2>
<hr color="green" width="300">
<form name="f" action="insert.jsp" method="post">
<table border="1">
<tr>
<td align="center">
아이디 : <input type="text" name="id"><br>
학생명 : <input type="text" name="name"><br>
학급명 : <input type="text" name="cname"><br>
<input type="submit" value="전송">
<input type="reset" value="취소">
</td>
</tr>
</table>
</form>
<hr color="green" width="300">
<h2> 학 생 삭 제 페 이 지 </h2>
<hr color="green" width="300">
<form name="f" action="delete.jsp" method="post">
<table border="1">
<tr>
<td align="center">
아이디 : <input type="text" name="id"><br>
<input type="submit" value="삭제">
</td>
</tr>
</table>
</form>
<hr color="green" width="300">
<h2> 학 생 찾 기 페 이 지 </h2>
<hr color="green" width="300">
<form name="f" action="find.jsp" method="post">
<table border="1">
<tr>
<td align="center">
학급명 : <input type="text" name="cname"><br>
<input type="submit" value="찾기">
</td>
</tr>
</table>
</form>
<hr color="green" width="300">
<h2> 학 생 목 록 페 이 지 </h2>
<hr color="green" width="300">
<form name="f" action="list.jsp" method="post">
<table border="1">
<tr>
<td align="center">
<input type="submit" value="목록">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
* insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>insert</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
//String id = request.getParameter("id");
//String name = request.getParameter("name");
//String cname = request.getParameter("cname");
%>
<jsp:useBean id="stdto" class="student.StudentDTO" />
<jsp:setProperty property="*" name="stdto"/>
<!--
<jsp:setProperty> 태그를 통해서 축약할 수 있는 원래 코드
StudentDTO stdto = new StudentDTO;
stdto.setId(request.getParameter("id"));
-->
<%
if(stdto.getId() == null || stdto.getName() == null || stdto.getCname() == null
|| stdto.getId().trim().equals("") || stdto.getName().trim().equals("")
|| stdto.getCname().trim().equals("") ){
%>
<script type="text/javascript">
alert("아이디, 학생명, 학급명을 모두 입력해 주세요!")
history.back()
</script>
<%
return;
}
%>
<jsp:useBean id="stdao" class="student.StudentDAO"/>
<%
int res = stdao.insertStudent(stdto);
if(res > 0){
%>
<script type="text/javascript">
alert("학생등록 성공! 학생목록페이지로 이동합니다.")
location.href="list.jsp";
</script>
<%
} else{
%>
<script>
alert("학생등록 실패! 학생등록페이지로 이동합니다.")
location.href="student.jsp"
</script>
<%
}
%>
</body>
</html>
* insert.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!-- insert.jsp -->
<%
request.setCharacterEncoding("UTF-8");
//String id = request.getParameter("id");
//String name = request.getParameter("name");
//String cname = request.getParameter("cname");
%>
<jsp:useBean id="stdto" class="student.StudentDTO"/>
<jsp:setProperty property="*" name="stdto"/>
<!-- StudentDTO stdto = new StudentDTO();
stdto.setId(request.getParameter("id")); -->
<% if (stdto.getId()==null || stdto.getName()==null ||
stdto.getCname()==null || stdto.getId().trim().equals("") ||
stdto.getName().trim().equals("") || stdto.getCname().trim().equals("")){%>
<script type="text/javascript">
alert("아이디, 학생명, 학급명을 모두 입력해 주세요!!")
history.back()
</script>
<% return;
}%>
<jsp:useBean id="stdao" class="student.StudentDAO"/>
<% int res = stdao.insertStudent(stdto);
if (res>0){%>
<script type="text/javascript">
alert("학생등록 성공!! 학생목록페이지로 이동합니다.")
location.href="list.jsp"
</script>
<% }else {%>
<script type="text/javascript">
alert("학생등록 실패!! 학생등록페이지로 이동합니다.")
location.href="student.jsp"
</script>
<% } %>
* list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*, student.*"%>
<!-- list.jsp -->
<html>
<head>
<title>학생목록</title>
</head>
<body>
<div align="center">
<hr color="green" width="300">
<h2> 학 생 목 록 페 이 지 </h2>
<hr color="green" width="300">
<table border="1" width="500">
<tr>
<th>아이디</th>
<th>이름</th>
<th>학급명</th>
</tr>
<jsp:useBean id="stdao" class="student.StudentDAO"/>
<%
List<StudentDTO> list = stdao.listStudent();
if(list == null || list.size() == 0){
%>
<tr>
<td colspan="3">등록된 학생이 없습니다.</td>
</tr>
<%
} else{
for(StudentDTO dto : list){
%>
<tr>
<td><%=dto.getId() %></td>
<td><%=dto.getName() %></td>
<td><%=dto.getCname() %></td>
</tr>
<%
}
}
%>
</table>
</div>
</body>
</html>
* find.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*, student.*"%>
<!-- find.jsp -->
<%
request.setCharacterEncoding("UTF-8");
String cname = request.getParameter("cname");
if(cname == null || cname.trim().equals("")){
response.sendRedirect("student.jsp");
return;
}
%>
<html>
<head>
<title>학생찾기</title>
</head>
<body>
<div align="center">
<hr color="green" width="300">
<h2> <%=cname %>학급 학생목록 </h2>
<hr color="green" width="300">
<table border="1" width="500">
<tr>
<th>아이디</th>
<th>이름</th>
<th>학급명</th>
</tr>
<jsp:useBean id="stdao" class="student.StudentDAO"/>
<%
List<StudentDTO> list = stdao.findStudent(cname);
if(list == null || list.size() == 0){
%>
<tr>
<td colspan="3"><%=cname %>학급의 학생정보가 없습니다.</td>
</tr>
<%
}
for(StudentDTO dto : list){
%>
<tr>
<td><%=dto.getId() %></td>
<td><%=dto.getName() %></td>
<td><%=cname %></td>
</tr>
<%
}
%>
</table>
</div>
</body>
</html>
* delete.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.sql.*"%>
<!-- delete.jsp -->
<%
String id = request.getParameter("id");
if(id == null || id.trim().equals("")){
response.sendRedirect("student.jsp");
return;
}
%>
<jsp:useBean id="stdao" class="student.StudentDAO"/>
<%
int res = stdao.deleteStudent(id);
if(res > 0){
%>
<script type="text/javascript">
alert('삭제가 완료되었습니다.')
location.href="list.jsp"
</script>
<%
} else{
%>
<script type="text/javascript">
alert('삭제에 실패했습니다. 존재하지 않는 아이디입니다.')
location.href="student.jsp"
</script>
<%
}
%>
'IT&코딩 > 자바 프로젝트' 카테고리의 다른 글
자바 프로젝트 6일차 - Servlet (testServlet) (0) | 2023.01.26 |
---|---|
자바 프로젝트 5일차 - JSP 복습 3 (jspMember) (0) | 2023.01.24 |
자바 프로젝트 4일차 - JSP 복습 2 (jspBoard) (2) | 2023.01.22 |
자바 프로젝트 2일차 - Java 복습2 (0) | 2023.01.21 |
자바 프로젝트 1일차 - Java 복습 1 (0) | 2023.01.14 |