Q. 이메일 리스트를 관리하는 JSP 웹 응용프로그램을 작성합니다.
1. DB테이블 생성
CREATE TABLE emaillist (
no NUMBER PRIMARY KEY,
last_name VARCHAR2(20) NOT NULL,
first_name VARCHAR2(20) NOT NULL,
email VARCHAR2(128) NOT NULL,
createdAt DATE DEFAULT SYSDATE);
CREATE SEQUENCE seq_emaillist_pk
START WITH 1
INCREMENT BY 1;
1-1. sample 데이터 삽입
INSERT INTO emaillist (no, first_name, last_name, email)
VALUES(seq_emaillist_pk.nextval , 'LIM','jaemin','jmeeen@gmail.com');
2. JAVA VO객체 생성
-> DB를 읽어와서 저장할 하나의 객체, 한명한명의 데이터 그룹이다.
- 이왕이면 필드는 '_' 이런거 붙이지 말고 소문자로 만드는게 낫다.
package com.example.emaillist.vo;
import java.util.Date;
public class EmailVO {
// 필드
private Long no;
private String lastname;
private String firstname;
private String email;
private Date createdAt;
//생성자
public EmailVO(Long no, String lastname, String firstname, String email, Date createdAt) {
this.no = no;
this.last_name = lastname;
this.first_name = firstname;
this.email = email;
this.createdAt = createdAt;
}
// Getter /setter
public Long getNo() {
return no;
}
public void setNo(Long no) {
this.no = no;
}
public String getLastname() {
return lastname;
}
public void setLast_name(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirst_name(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
@Override
public String toString() {
return "EmailVO [no=" + no + ", last_name=" + last_name + ", first_name=" + first_name + ", email=" + email
+ ", createdAt=" + createdAt + "]";
}
}
3. JAVA DAO 생성
-> 인터페이스다. 기능들을 만들겠다고 사전에 정의를 한다.
package com.example.emaillist.dao;
import java.util.List;
import com.example.emaillist.vo.EmailVO;
public interface EmaillistDao {
public List<EmailVO> getlist();
public int insert(EmailVO vo);
public int delete(Long pk);
}
4. JAVA DAO IMpl 생성
- 드라이버 생성 하고 접속하는것을 따로 만든다.
- 각 필요한 메뉴에 따라 별도로 SQL문을 작성한다.
package com.example.emaillist.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import com.example.emaillist.vo.EmailVO;
public class EmaillistDaoImpl implements EmaillistDao {
private Connection getConnection() throws SQLException {
Connection conn = null;
try {
// 드라이버 로드
Class.forName("oracle.jdbc.driver.OracleDriver");
// Connection 가져오기
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", // DBURL
"C##BITUSER", // DB User
"bituser");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로드 실패");
e.printStackTrace();
}
return conn;
}
@Override
public List<EmailVO> getlist() {
List<EmailVO> list = new ArrayList<>();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
String sql = "SELECT no, last_name, first_name, email, createdAt " + " FROM emaillist ORDER BY no DESC";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// 데이터 받아오고
// 데이터 받기
Long no = rs.getLong(1);
String lastName = rs.getString(2);
String firstName = rs.getString(3);
String email = rs.getString(4);
Date createdAt = rs.getDate(5);
// VO 객체 생성
EmailVO vo = new EmailVO();
vo.setNo(no);
vo.setLastname(lastName);
vo.setFirstname(firstName);
vo.setEmail(email);
vo.setCreatedAt(createdAt);
// 리스트에 추가
list.add(vo);
}
} catch (SQLException e) {
System.err.println("SQL 에러!!!");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(list);
return list;
}
@Override
public int insert(EmailVO vo) {
int count = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
// 실행 계획
String sql = "INSERT INTO emaillist " + "(no, last_name, first_name, email) "
+ " VALUES(seq_emaillist_pk.NEXTVAL, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
// 파라미터 바인딩
pstmt.setString(1, vo.getLastname());
pstmt.setString(2, vo.getFirstname());
pstmt.setString(3, vo.getEmail());
// 쿼리 수행
count = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return count;
}
@Override
public int delete(Long pk) {
int deletedCount = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String sql = "DELETE FROM emaillist Where no =?";
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, pk);
deletedCount = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return deletedCount;
}
}
5. index.html 에서 index.jsp를 연결
index. html을 오픈하면 하이퍼링크로 "이메일 리스트 목록"으로 연결하게 해두었다.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello HTML</title>
</head>
<body>
<H3> Emaillist (model 1)</H3>
<p>
<a href="/web/emaillist/">이메일 리스트(Model 1) 목록</a>
</p>
</body>
</html>
특정 파일/서비스를 명시하지 않았을때 emailist.jsp를 기본으로 띄운다.
<!-- 특정파일/ 서비스 명시하지 않았을 떄 보여줄 기본 페이지 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
6. index.jsp 설정
- HTML문서에서 Java 명령어를 가져올땐 <%= ~ %>를 사용한다. 길어지면 굉장히 보기 어려워지므로 주의.
- 처음에 이메일리스트를 바로 받아온다. EmaillistDaoimple의 getlist를 사용한다.
- 중요한 것은 버튼이나 링크의 name이 parameter명이 되는데, 대소문자를 매우 까다롭게 따지니 주의.
- 아직 폼의 정확한 길이는 지정하지 않아 유동적으로 변경되는것 같다.
<%@page import="com.example.emaillist.vo.EmailVO"%>
<%@page import="java.util.List"%>
<%@page import="com.example.emaillist.dao.EmaillistDaoImpl"%>
<%@page import="com.example.emaillist.dao.EmaillistDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
EmaillistDao dao = new EmaillistDaoImpl();
// 이메일 리스트 받아오기
List<EmailVO> list = dao.getlist();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Emaillist (Model 1)</title>
</head>
<body>
<h1>메일링 리스트(Model 1)</h1>
<!-- 이메일 리스트 : 목록 -->
<!-- 루프 시작 -->
<%
for (EmailVO vo : list) {
%>
<table border="1">
<!-- 행 -->
<tr>
<th>성</th>
<td><%=vo.getLastname()%></td>
<td></td>
</tr>
<tr>
<th>이름</th>
<td><%=vo.getFirstname()%></td>
<td></td>
</tr>
<tr>
<th>이메일</th>
<td><%=vo.getEmail()%></td>
<td></td>
</tr>
<tr>
<td colspan="2">
<!-- 삭제폼 -->
<form action="<%=request.getContextPath()%>/emaillist/delete.jsp"
method="post">
<input type="hidden" name="no" value="<%=vo.getNo()%>">
<input type="submit" VALUE="삭제">
</form>
</td>
</tr>
</table>
<br />
<%
}
%>
<!-- 루프의 끝 -->
<!-- 작성 폼으로 이동 -->
<P>
<a href="<%=request.getContextPath()%>/emaillist/form.jsp">추가 이메일
등록</a>
</body>
</html>
request.getContextPath() 함수 = 프로젝트 Path를 가져온다.
7. 추가 이메일 등록
- form.jsp로 연결한다고 index.jsp 제일 하단에 적어두었다.
- 이 보이는 문서는 단순히 Form이다. 추가로 연결되는것이 insert.jsp로 이동한다고 했다.
- label의 name 또한 대소문자를 구분하니 주의하도록!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>메일링 리스트 가입(Model 1)</h1>
<p>
메일링 리스트에 가입하려면<br> 아래 항목을 기입하고 등록 버튼을 눌러 주세요
</p>
<!-- action : 요청을 처리할 페이지(서블릿/jsp) 메서드 : 요청방식 -->
<form action="<%=request.getContextPath()%>/emaillist/insert.jsp"
method="post">
<label for="Last_name">성</label>
<input type="text" name="last_name" id="Last_name"><br>
<label for="First_name">이름</label>
<input type="text" name="first_name" id="First_name"><br>
<label for="email">이메일</label>
<input type="text" name="email" id="email"><br>
<!-- 전송 버튼 -->
<input type="submit" value="등록">
</form>
<!-- 리스트로 돌아가기 -->
<p>
<a href="<%=request.getContextPath()%>/emaillist/">목록 보기</a>
</p>
</body>
</html>
아래의 내용이 Insert를 해결하는 jsp이다.
순서는 등록버튼을 누르면 insert.jsp가 실행되고, 여기서 파라메터값을 취합하여 EmaillistDaoImple의 insert로 넘기기.
<%@page import="com.example.emaillist.vo.EmailVO"%>
<%@page import="com.example.emaillist.dao.EmaillistDaoImpl"%>
<%@page import="com.example.emaillist.dao.EmaillistDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 파라미너 받아오기
String lastName = request.getParameter("last_name");
String firstName = request.getParameter("first_name");
String email = request.getParameter("email");
// 파라미터 확인
//DAO
EmaillistDao dao = new EmaillistDaoImpl();
// vo객체 생성
EmailVO vo = new EmailVO();
vo.setLastname(lastName);
vo.setFirstname(firstName);
vo.setEmail(email);
dao.insert(vo);
// INDEX.jsp로 리다이렉트(페이지전환 302)
response.sendRedirect(request.getContextPath()+"/emaillist/");
%>
8. 삭제
- 등록과 같지만, form이 없다. 같은 form에서 연결된다.
- 6)의 메일링 리스트를 보면 삭제 폼 이라는 부분의 name="no" 라는 부분의 번호를 가져온다.
<%@page import="com.example.emaillist.dao.EmaillistDaoImpl"%>
<%@page import="com.example.emaillist.dao.EmaillistDao"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 파라미터 받기
Long pk = Long.valueOf(request.getParameter("no"));
// DAO 불러오기
EmaillistDao dao = new EmaillistDaoImpl();
//삭제
dao.delete(pk);
// index.jsp로 리다이렉트
response.sendRedirect(request.getContextPath()+"/emaillist/");
%>
머리가 터질거같지만. 일단 완성.
'Web Programming' 카테고리의 다른 글
MVC패턴 - 회원가입/ 로그인 구현 (0) | 2021.08.17 |
---|---|
웹프로그래밍 - MVC 패턴 (0) | 2021.08.17 |
JSP 태그 (0) | 2021.08.13 |
Servlet & JSP 기초 - 2 (0) | 2021.08.13 |
Servlet & JSP 기초 (0) | 2021.08.12 |