[ 프로그램 진행 원리 및 개요 ]
> 1번 기능 : 상품 등록 기능
register-form.jsp -- command:register --> RegisterProductController <--> ProductDAO
ㅣ register(ProductDAO)
ㅣredirect
register-result.jsp
> 2번 기능 : 전체 상품 목록 조회 기능 (아이디, 상품명, 등록날짜만)
index.jsp에서 '상품목록'링크 클릭 -- command=getlist --> ProductListController <--> ProductDAO
ㅣ getAllProductList() : ArrayList<ProductVO>
ㅣforward
product-list.jsp
아이디, 상품명, 등록시간 테이블로 제공
> 3번 기능 : 상품 상세 정보 링크 제공 기능
product-list.jsp에서 'name' 클릭 -- command=detailproduct&id=id --> ProductInfoController <--> ProductDAO
ㅣ findProductById(String id) : ProductVO
ㅣforward
product-detail.jsp
[ 전체 구현 코드 ]
Model
/ProductDAO.java
package org.kosta.model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class ProductDAO {
//Singleton pattern 적용
private static ProductDAO instance = new ProductDAO();
//JDBC에 필요한 변수
private String driver = "oracle.jdbc.OracleDriver";
private String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
private String username = "scott";
private String userpass = "tiger";
//private 생성자 + driver loading
private ProductDAO () {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//객체 생성용(반환용)
public static ProductDAO getInstance() {
return instance;
}
//getConnection():Connection method
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, userpass);
}
//closeAll method 1
public void closeAll(PreparedStatement pstmt, Connection con)
throws SQLException {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
}
//closeAll method 2
public void closeAll(ResultSet rs, PreparedStatement pstmt, Connection con)
throws SQLException {
if (rs != null)
rs.close();
//재사용
this.closeAll(pstmt, con);
}
/*
* 1번 기능 : 상품 등록
* register(ProductVO)
*/
public void register(ProductVO vo) throws SQLException {
Connection con = getConnection();
PreparedStatement pstmt = null;
try {
StringBuilder sql = new StringBuilder();
sql.append("INSERT INTO mvc_product(id, name, maker, price, regdate) ");
sql.append("VALUES (mvc_product_seq.nextval, ?, ?, ?, sysdate)");
pstmt = con.prepareStatement(sql.toString());
pstmt.setString(1, vo.getName());
pstmt.setString(2, vo.getMaker());
pstmt.setInt(3, vo.getPrice());
pstmt.executeUpdate();
} finally {
closeAll(pstmt, con);
}
}
/*
* 2번 기능 : 전체 상품 조회 기능
* getAllProductList() : ArrayList<ProductVO>
*/
public ArrayList<ProductVO> getAllProductList() throws SQLException{
ArrayList<ProductVO> list = new ArrayList<ProductVO>();
Connection con = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT id, name, TO_CHAR(regdate, 'YYYY/MM/DD') "
+ "FROM mvc_product";
pstmt = con.prepareStatement(sql);
rs = pstmt.executeQuery();
while(rs.next()) {
ProductVO vo = new ProductVO();
vo.setId(rs.getString(1));
vo.setName(rs.getString(2));
vo.setRegDate(rs.getString(3));
list.add(vo);
}
} finally {
closeAll(rs, pstmt, con);;
}
return list;
}
/*
* 3번 기능 : 아이디로 상품 정보 찾기 기능
* findProductById(String id) : ProductVO
*/
public ProductVO findProductById(String id) throws SQLException {
ProductVO vo = null;
Connection con = getConnection();
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
String sql = "SELECT * FROM mvc_product WHERE id=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
vo = new ProductVO();
vo.setId(id);
vo.setName(rs.getString("name"));
vo.setMaker(rs.getString("maker"));
vo.setPrice(rs.getInt("price"));
vo.setRegDate(rs.getString("regdate"));
}
} finally {
closeAll(rs, pstmt, con);
}
return vo;
}
}//class
/ProductVO.java
package org.kosta.model;
public class ProductVO {
private String id;
private String name;
private String maker;
private int price;
private String regDate;
public ProductVO() {
super();
}
public ProductVO(String id, String name, String maker,
int price, String regDate) {
super();
this.id = id;
this.name = name;
this.maker = maker;
this.price = price;
this.regDate = regDate;
}
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 getMaker() {
return maker;
}
public void setMaker(String maker) {
this.maker = maker;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getRegDate() {
return regDate;
}
public void setRegDate(String regDate) {
this.regDate = regDate;
}
@Override
public String toString() {
return "ProductVO [id=" + id + ", name=" + name + ", maker=" + maker
+ ", price=" + price + ", regDate="+ regDate + "]";
}
}
View
/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<head>
<meta charset="UTF-8">
<title>HOME</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
</head>
<body>
<div class="container">
<a href="index.jsp"><img class="home-image" src="home.png">Home</a>
<a href="register-form.jsp">상품등록</a>
<a href="front?command=getlist">상품목록</a>
<hr>
</div>
</body>
</html>
/error.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>
<marquee>
시스템 에러가 발생했습니다. 콘솔을 확인하세요!<br>
<br> <img src="error.jpg">
</marquee>
</body>
</html>
-- 1번 기능 : 상품 등록 기능
/register-form.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<head>
<meta charset="UTF-8">
<title>상품등록 form</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
</head>
<body>
<div class="container">
<a href="index.jsp"><img class="home-image" src="home.png">Home</a>
<a href="product-list.jsp">상품목록</a>
<hr>
<h3>상품등록</h3>
<form action="front" method="post">
<input type="hidden" name="command" value="register">
상품명 <input type="text" name="name" required="required"><br>
제조사 <input type="text" name="maker" required="required"><br>
가격 <input type="number" name="price" required="required"><br>
<input type="submit" value="등록하기"><br>
</form>
</div>
</body>
</html>
/register-result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<head>
<meta charset="UTF-8">
<title>등록 완료</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
</head>
<body>
<div class="container">
<a href="index.jsp"><img class="home-image" src="home.png">Home</a>
<a href="register-form.jsp">상품등록</a>
<hr>
<h4>상품 등록이 완료되었습니다</h4>
</div>
</body>
</html>
-- 2번 기능 : 전체 상품 목록 조회 기능 (아이디, 이름, 등록날짜만) + Table 형태로 보여주기
+ 3번 기능의 링크가 포함되어 있다
/product-list.jsp
<%@page import="org.kosta.model.ProductVO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<head>
<meta charset="UTF-8">
<title>상품 목록 테이블</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
</head>
<body>
<div class="container">
<a href="index.jsp"><img class="home-image" src="home.png">Home</a>
<a href="register-form.jsp">상품등록</a>
<hr>
<%
@SuppressWarnings("unchecked")
ArrayList<ProductVO> list
= (ArrayList<ProductVO>) request.getAttribute("list"); %>
<table>
<thead>
<tr>
<th>아이디</th>
<th>이름</th>
<th>등록날짜</th>
</tr>
</thead>
<tbody>
<% for(ProductVO vo:list) { %>
<tr>
<td><%=vo.getId() %></td>
<td><a href="front?command=detailproduct&id=<%=vo.getId()%>"><%=vo.getName() %></a></td>
<td><%=vo.getRegDate() %></td>
</tr>
<% } %>
</tbody>
</table>
</div>
</body>
</html>
-- 3번 기능 : product-list.jsp에서 이름을 클릭하면 id 정보가 response되어, 상품 상세 정보 보여주기
/iproduct-detail.jsp
<%@page import="org.kosta.model.ProductVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" session="false"%>
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<head>
<meta charset="UTF-8">
<title>상품 상세 정보</title>
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
</head>
<body>
<div class="container">
<a href="index.jsp"><img class="home-image" src="home.png">Home</a>
<a href="register-form.jsp">상품등록</a>
<a href="front?command=getlist">상품목록</a>
<hr>
<% ProductVO pvo = (ProductVO) request.getAttribute("pvo"); %>
<table>
<thead>
<tr>
<th>이름</th>
<th>제조사</th>
<th>가격</th>
<th>등록일시</th>
</tr>
</thead>
<tbody>
<tr>
<td><%=pvo.getName() %></td>
<td><%=pvo.getMaker() %></td>
<td><%=pvo.getPrice() %>원</td>
<td><%=pvo.getRegDate() %></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Controller
/DispatcherServlet.java
package org.kosta.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/front")
public class DispatcherServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HandleRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HandleRequest(request, response);
}
/* handleRequest method()
* 1. 모든 예외는 redirect 방식으로 error.jsp로 response(응답)한다.
* 2. Client가 전송한 command를 return 받아 온다.
* 3. HanlerMapping에게 command를 전달하여 개별 Controller 객체를 리턴 받는다.
* 4. 개별 Controller 객체를 실행시켜 url을 반환받는다.
* 5. 개별 Controller 객체가 실행된 후 반환한 정보를 이용해,
* forward 방식으로 보낼지, redirect 방식으로 보낼지 조건문을 이용해 확인 후,
* view로 이동한다.
*/
public void HandleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String command = request.getParameter("command");
Controller controller = HandlerMapping.getInstance().create(command);
String url = controller.execute(request, response);
if (url.startsWith("redirect:"))
response.sendRedirect(url.substring(9));
else
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
response.sendRedirect("error.jsp");
}
}
}
/ HandlerMapping.java
Factory 객체
-> Controller 객체 생성은 전담한다.
package org.kosta.controller;
/*
* Factory 객체
* -> Controller 객체 생성은 전담한다.
*/
public class HandlerMapping {
//static 초기화 시 한번만 만들어짐
private static HandlerMapping instance = new HandlerMapping();
//외부에서 생성 불가능하게 한다
private HandlerMapping() {}
//static해서 만든 instance를 외부에서 공유한다
public static HandlerMapping getInstance() {
return instance;
}
//create(String command) : Controller 객체 생성 메서드
public Controller create(String command) {
Controller controller = null;
if (command.contentEquals("register"))
controller = new RegisterProductController();
else if (command.contentEquals("getlist"))
controller = new ProductListController();
else if (command.contentEquals("detailproduct"))
controller = new ProductInfoController();
return controller;
}
}
/Controller.java
Controller Interface
-> 계층구조 형성을 통한 다형성 적용
-> 결합도를 낮추어 유지 보수성 향상 (DispatcherServlet과 개별 컨트롤러 객체 간 결합도 감소)
package org.kosta.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Controller {
//String type으로 url을 반환
public String execute(HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
-- 1번 기능 : 상품 등록 기능 controller
/RegisterProductController.java
package org.kosta.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.kosta.model.ProductDAO;
import org.kosta.model.ProductVO;
public class RegisterProductController implements Controller {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response)
throws Exception {
ProductVO vo = new ProductVO();
vo.setName(request.getParameter("name"));
vo.setMaker(request.getParameter("maker"));
vo.setPrice(Integer.parseInt(request.getParameter("price")));
ProductDAO.getInstance().register(vo);
return "redirect:register-result.jsp";
}
}
-- 2번 기능 : 전체 상품 목록 조회 기능 controller
/ProductListController.java
package org.kosta.controller;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.kosta.model.ProductDAO;
import org.kosta.model.ProductVO;
public class ProductListController implements Controller {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response)
throws Exception {
ArrayList<ProductVO> list = new ArrayList<ProductVO>();
list = ProductDAO.getInstance().getAllProductList();
request.setAttribute("list", list);
return "product-list.jsp";
}
}
-- 3번 기능 : 상품 상세정보 제공 링크 기능 controller
/ProductInfoController.java
package org.kosta.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.kosta.model.ProductDAO;
import org.kosta.model.ProductVO;
public class ProductInfoController implements Controller {
@Override
public String execute(HttpServletRequest request, HttpServletResponse response)
throws Exception {
String id = request.getParameter("id");
ProductVO vo = ProductDAO.getInstance().findProductById(id);
request.setAttribute("pvo", vo);
return "product-detail.jsp";
}
}
브라우저 결과 화면
'Java Web Programming > 4. JSP' 카테고리의 다른 글
[부트스트랩/BootStrap] 반응형 웹, 미디어쿼리, 부트스트랩(그리드, 테이블) (0) | 2020.09.14 |
---|---|
[JSP] DBCP + Model2 MVC Pattern (+ 각 객체 개념설명) (0) | 2020.09.14 |
[JSP] Cookie 쿠키 & Session 세션 + Model 2 Architecture (MVC Pattern) 설계방식을 다시 한 번 정리하고 가자! (0) | 2020.09.04 |
[JSP/세션관리] 2단계_Cookie 쿠키 & Session 세션을 이용한 회원정보 수정 및 회원가입 프로그램 구현 (+아이디 중복 확인) (0) | 2020.09.04 |
[JSP/세션관리] 1단계_Cookie 쿠키 & Session 세션을 이용한 로그인 유지 프로그램 구현 (2) | 2020.09.01 |