0. 웰컴화면 생성
0.1. Dynamic Web Project 생성
0.2 화면 생성(jsp나 html)
WebContent > index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="main.com.kh.subway.common.JDBCTemplate" %>
<%
JDBCTemplate.getConnection();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>안녕하세요 서브웨이입니다 ~ </title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100&family=Roboto+Condensed:wght@300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<style>
body {
margin : 0px;
padding : 0px;
color:blanchedalmond;
}
#img{
display: none;
position: absolute;
top : 250px;
left : 1100px;
}
#title{
margin-top:40px;
text-align:center;
font-size:45px;
}
#title1{
color: #ffce32;
}
#title2{
color: #009223;
}
#header {
background-color: white;
padding-bottom: 10px;
line-height:100px
}
#btn-zone{
text-align:right;
padding-right: 20px;
}
.wrap{
width : 820px;
height : 830px;
margin : auto;
}
.content{
font-family: 'Noto Sans KR', sans-serif;
font-weight: bold;
background-color: #009222;
border-radius: 20px;
}
table {
border-collapse: separate;
border-spacing: 0 5px;
}
input[type=checkbox]{
margin-right: 10px;
margin-left : 5px;
}
th, legend{
padding-left: 20px;
}
a {
text-decoration: none;
color: crimson;
}
</style>
</head>
<body>
<div class="wrap">
<div id="header">
<h1 id="title">
<span id="title1">SUB</span><span id="title2">WAY</span>
</h1>
</div>
<div class="content">
<br><br>
<form action="/subway/order.do" method="get">
<fieldset>
<legend>주문자 정보</legend>
<table>
<tr>
<th width="130">이름</th>
<td><input type="text" name="userName" class="form-control" required></td>
</tr>
<tr>
<th>전화번호</th>
<td><input type="text" name="phone" class="form-control" required></td>
</tr>
<tr>
<th>주소</th>
<td><input type="text" name="address" class="form-control" required></td>
</tr>
<tr>
<th>요청사항</th>
<td><textarea name="message" cols="80" rows="5" class="form-control" style="resize:none"></textarea></td>
</tr>
</table>
</fieldset>
<br>
<fieldset>
<legend>주문 정보</legend>
<table>
<tr>
<th width="130">샌드위치</th>
<td>
<select name="sandwich" class="form-control">
<option>스파이시 바비큐</option>
<option>스파이시 쉬림프</option>
<option>스테이크 & 치즈</option>
<option>로티세리 바비큐 치킨</option>
<option>스파이시 바비큐</option>
<option>K-바비큐</option>
<option>풀드 포크 바비큐</option>
<option>머쉬룸</option>
<option>쉬림프</option>
<option>로스트 치킨</option>
<option>치킨 데리야끼</option>
<option>서브웨이 클럽</option>
<option>치킨 슬라이스</option>
<option>참치</option>
<option>에그마요</option>
<option>이탈리안 비엠티</option>
<option>터키 베이컨 아보카도</option>
</select>
</td>
</tr>
<tr>
<th>채소</th>
<td>
<input type="checkbox" name="vegetable" value="오이" checked><label>오이</label>
<input type="checkbox" name="vegetable" value="양배추" checked>양배추
<input type="checkbox" name="vegetable" value="올리브" checked>올리브
<input type="checkbox" name="vegetable" value="할라피뇨" checked>할라피뇨
<input type="checkbox" name="vegetable" value="적양파" checked>적양파
<input type="checkbox" name="vegetable" value="피망" checked>피망
<input type="checkbox" name="vegetable" value="토마토" checked>토마토
</td>
</tr>
<tr>
<th>소스</th>
<td>
<input type="checkbox" name="sauce" value="랜치">랜치
<input type="checkbox" name="sauce" value="후추">후추
<input type="checkbox" name="sauce" value="스위트 어니언">스위트 어니언
<input type="checkbox" name="sauce" value="스위트 칠리">스위트 칠리
<input type="checkbox" name="sauce" value="핫칠리">핫 칠리
<input type="checkbox" name="sauce" value="마요네즈">마요네즈
<input type="checkbox" name="sauce" value="홀스래디쉬">홀스래디쉬
</td>
</tr>
<tr>
<td></td>
<td>
<input type="checkbox" name="sauce" value="스모크 바비큐">스모크 바비큐
<input type="checkbox" name="sauce" value="허니 머스타드">허니 머스타드
<input type="checkbox" name="sauce" value="사우스웨스트 치폴레">사우스웨스트 치폴레
<input type="checkbox" name="sauce" value="이탈리안 드레싱">이탈리안 드레싱
</td>
</tr>
<tr>
<th>쿠키</th>
<td>
<input type="checkbox" name="cookie" value="라즈베리치즈케잌">라즈베리치즈케잌
<input type="checkbox" name="cookie" value="더블초코칩쿠키">더블초코칩쿠키
<input type="checkbox" name="cookie" value="스모어초코어쩌고">스모어초코어쩌고
</td>
</tr>
<tr>
<th>결제방식</th>
<td>
<input type="radio" name="payment" value="card" checked> 카드결제
<input type="radio" name="payment" value="cash"> 현금결제
</td>
</tr>
</table>
</fieldset>
<br>
<hr>
<div id="btn-zone">
<input type="submit" class="btn btn-info" value="주문하기">
<input type="reset" class="btn btn-warning" value="초기화">
</div>
</form>
<br>
</div>
<br>
</div>
<a href='/subway/orderList.sandwich'>주문내역보기</a>
<br>
<div id="img">
<img id="sandimg" src="">
</div>
<script>
var timeOut;
$(() => {
$('select').change(function() {
if(timeOut != undefined){
clearTimeout(timeOut);
}
const sand = $(this).val();
sandwich = {
'스파이시 바비큐' : 'https://www.subway.co.kr/upload/menu/%EC%8A%A4%ED%8C%8C%EC%9D%B4%EC%8B%9C%EB%B0%94%EB%B9%84%ED%81%90_%EC%A0%95%EB%A9%B4_20221031041334845.png',
'스파이시 쉬림프' : 'https://www.subway.co.kr/upload/menu/Spicy_Shrimp_front_20230703125534663.png',
'스테이크 & 치즈' : 'https://www.subway.co.kr/upload/menu/Steak-&-Cheese_20211231095455613.png',
'스파이시 이탈리안' : 'https://www.subway.co.kr/upload/menu/spicy_italian_20211231095435532.png',
'로티세리 바비큐 치킨' : 'https://www.subway.co.kr/upload/menu/Rotisserie-Barbecue-Chicken_20211231023137878.png',
'스파이시 바비큐' : 'https://www.subway.co.kr/upload/menu/%EC%8A%A4%ED%8C%8C%EC%9D%B4%EC%8B%9C%EB%B0%94%EB%B9%84%ED%81%90_%EC%A0%95%EB%A9%B4_20221031041334845.png',
'K-바비큐' : 'https://www.subway.co.kr/upload/menu/K-BBQ_20211231094930225.png',
'풀드 포크 바비큐' : 'https://www.subway.co.kr/upload/menu/Pulled-Pork+cheese_20211231095012512.png',
'머쉬룸' : 'https://www.subway.co.kr/upload/menu/%EB%A8%B8%EC%89%AC%EB%A3%B8_%EC%83%8C%EB%93%9C%EC%9C%84%EC%B9%98_20220715112921467.png',
'쉬림프' : 'https://www.subway.co.kr/upload/menu/Shrimp_20211231095411189.png',
'로스트 치킨' : 'https://www.subway.co.kr/upload/menu/Roasted-Chicken_20211231095032718.png',
'치킨 데리야끼' : 'https://www.subway.co.kr/upload/menu/Chicken-Teriyaki_20211231094803381.png',
'서브웨이 클럽' : 'https://www.subway.co.kr/upload/menu/Subway-Club%E2%84%A2_20211231095518589.png',
'치킨 슬라이스' : 'https://www.subway.co.kr/upload/menu/%EC%B9%98%ED%82%A8%EC%8A%AC%EB%9D%BC%EC%9D%B4%EC%8A%A4%EC%83%8C%EB%93%9C%EC%9C%84%EC%B9%98_20220804012537491.png',
'참치' : 'https://www.subway.co.kr/upload/menu/Tuna_20211231095535268.png',
'에그마요' : 'https://www.subway.co.kr/upload/menu/Egg-Mayo_20211231094817112.png',
'이탈리안 비엠티' : 'https://www.subway.co.kr/upload/menu/Italian_B.M.T_20211231094910899.png',
'터키 베이컨 아보카도' : 'https://www.subway.co.kr/upload/menu/%EC%B9%98%ED%82%A8%EB%B2%A0%EC%9D%B4%EC%BB%A8%EC%95%84%EB%B3%B4%EC%B9%B4%EB%8F%84%EC%83%8C%EB%93%9C%EC%9C%84%EC%B9%98_20220804012954461.png'
};
$.each(sandwich, (k, v) => {
if(sand == k){
$('#sandimg').attr('src', sandwich[k]);
}
});
$('#img').show(1000);
timeOut = setTimeout(() => {
$('#img').hide(1000);
}, 4000);
});
});
</script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</body>
</html>
1. ORDER 테이블 생성
1-1. 계정 ROLE 부여
CREATE USER SUBWAY IDENTIFIED BY SUBWAY;
GRANT CONNECT, RESOURCE TO SUBWAY;
1-2. 테이블 생성
CREATE TABLE TB_ORDER(
USER_NAME VARCHAR2(20),
PHONE VARCHAR2(13),
ADDRESS VARCHAR2(200),
MESSAGE VARCHAR2(1000),
SANDWICH VARCHAR2(50),
VEGETABLE VARCHAR2(200),
SAUCE VARCHAR2(200),
COOKIE VARCHAR2(100),
PAYMENT VARCHAR2(12),
PRICE NUMBER,
ORDER_DATE DATE DEFAULT SYSDATE
);
SELECT * FROM TB_ORDER;
2. DB연결
2-1. 드라이브 연결
ojdbc의 Library에 드라이브가 있음. (ojdbc6.jar)를 WEB-INF > lib에 넣어주기.
src > main(java package) > sql(folder) > driver(folder) > driver.properties 에 DB 접속정보 입력
username=SUBWAY
password=SUBWAY
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
2-2. mapper / Template만들기
2-2-1. mapper 만들기
src > main(java package) > sql(folder) > mapper(folder) > subway-mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="insertOrder">
INSERT
INTO
TB_ORDER
VALUES
(
?,
?,
?,
?,
?,
?,
?,
?,
?,
?,
SYSDATE
)
</entry>
</properties>
2-2-2. JDBC Template 만들기
src > main(java package) > com > kh > suway > common > JDBCTemplate.java
package main.com.kh.subway.common;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCTemplate {
public static Connection getConnection() {
Connection conn = null;
Properties prop = new Properties();
// 읽어들이고자 하는 파일의 물리적인 경로
String fileName = JDBCTemplate.class.getResource("/main/sql/driver/driver.properties").getPath();
System.out.println(fileName);
try {
prop.load(new FileInputStream(fileName));
System.out.println(prop.getProperty("driver"));
Class.forName(prop.getProperty("driver"));
conn = DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"),
prop.getProperty("password"));
// 오토커밋 끄기
conn.setAutoCommit(false);
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void commit(Connection conn) {
try {
if(conn != null && !conn.isClosed()) {
conn.commit();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void rollback(Connection conn) {
try {
if(conn != null && !conn.isClosed()) {
conn.rollback();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Connection conn) {
try {
if(conn != null && !conn.isClosed()) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt) {
try {
if(stmt != null && !stmt.isClosed()) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rset) {
try {
if(rset != null && !rset.isClosed()) rset.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2-2-3. JDBC Template getConnection 메소드 호출
index.html에서 JDBC Template getConnection를 import 후 스크립틀릿으로 호출
<%@ page import="main.com.kh.subway.common.JDBCTemplate" %>
<%
JDBCTemplate.getConnection();
%>
3. JDBC
3-1. VO
src > main(java package) > com > kh > suway > model > vo
package main.com.kh.subway.model.vo;
import java.sql.Date;
public class Order {
private String userName;
private String phone;
private String address;
private String message;
private String sandwich;
private String vegetable;
private String sauce;
private String cookie;
private String payment;
private int price;
private Date orderDate;
// 생성자 getter setter toString
}
3-2. Controller
화면에서 입력한 값 받아서 처리할 servlet만들기
src > main(java package) > com > kh > suway > controller > SubwayOrderController.java(Servlet)
URL mapping값 : /order.do (== 앞단의 action값)
-- 이전에 JDBC와 다른 점
-정보뽑을 때 설정
-service로 전달할 때
package main.com.kh.subway.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import main.com.kh.subway.model.service.SubwayService;
import main.com.kh.subway.model.vo.Order;
/**
* Servlet implementation class SubwayOrderController
*/
@WebServlet("/order.do")
public class SubwayOrderController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SubwayOrderController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1) POST방식일 때 => 인코딩
//request.setCharacterEncoding("UTF-8");
// 2) 전달값이 있는가? => 값 뽑기 => request의 Parameter 영역에서
// request.getParameter("키값");
// request.getParameterValues("키값");
// 뽑아다가 변수에 담아두기
// 주문자 정보 뽑기!
// name속성값을 꼭 잘 getParameter인자값으로 넣어주기
String userName = request.getParameter("userName");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String message = request.getParameter("message");
// 주문 정보 뽑기!
String sandwich = request.getParameter("sandwich");
// checkbox == request.getParameterValues() : String[] => 체크된 게 하나도 없을 때 null
String[] vegetable = request.getParameterValues("vegetable");
String[] sauce = request.getParameterValues("sauce");
String[] cookie = request.getParameterValues("cookie");
String payment = request.getParameter("payment");
// 3) 가공 -> VO클래스를 객체로 생성해서 거기 담았음
// 요청 처리 간단하게
int price = 0;
// 가격책정
// 샌드위치에 따른 기본 가격
switch(sandwich) {
case "스파이시 바비큐" :
case "스파이시 쉬림프" :
case "스테이크 & 치즈" :
case "로티세리 바비큐" :
case "치킨스파이시 바비큐" :
case "K-바비큐" :
case "풀드 포크 바비큐" : price += 6500; break;
case "머쉬룸" :
case "쉬림프" :
case "로스트 치킨" :
case "치킨 데리야끼" :
case "서브웨이 클럽" : price += 5500; break;
case "치킨 슬라이스" :
case "참치에그마요" :
case "이탈리안 비엠티" :
case "터키 베이컨 아보카도" : price += 3400; break;
}
// 쿠키 종류에 따라서 추가금액 더하기
// 배열의 경우 체크된 게 없을 때 null이 와버림
// 무작정 반복문을 돌리면 NullPointerException이 발생할 가능성이 있음
// => if문으로 애초에 발생을 안하도록 막아주기!
if(cookie != null) {
for(int i = 0; i < cookie.length; i++) {
switch(cookie[i]) {
case "라즈베리치즈케잌" :
case "더블초코칩쿠키" :
case "스모어초코어쩌고" : price += 2300; break;
}
}
}
// VO 객체에 담기
Order order = new Order(userName,
phone,
address,
message,
sandwich,
String.join(",", vegetable),
String.join(",", sauce),
String.join(",", cookie),
payment,
price,
null // default값 SYSDATE를 넣어줘야 함
);
// 4) Service단으로 전달~
int result = new SubwayService().insertOrder(order);
// System.out.println(result);
// 수하물 부치기~ => request의 Attribute영역에 담기
request.setAttribute("sandwich", sandwich);
request.setAttribute("vagetable", vegetable);
request.setAttribute("sauce", sauce);
request.setAttribute("cookie", cookie);
request.setAttribute("payment", payment);
request.setAttribute("price", price);
// 응답 뷰 지정 => 응답화면 만들어줄 JSP로 포워딩
if(result > 0) {
RequestDispatcher view = request.getRequestDispatcher("view/result.jsp");
view.forward(request, response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
service에게 반환값 받고 난 뒤 결과값을 result.jsp에게 보내줘서 화면지정
Source > Override Method > innit, service, do, get, destroy 이런거 오버라이딩 해서 쓸수 있음 / extends로도
3-3. Service
src > main(java package) > com > kh > suway > model > service > SubwayService.java
controller에게 받은 값을 connection과 함께 dao에게 전달
package main.com.kh.subway.model.service;
import java.sql.Connection;
import main.com.kh.subway.common.JDBCTemplate;
import main.com.kh.subway.model.dao.SubwayDao;
import main.com.kh.subway.model.vo.Order;
public class SubwayService {
public int insertOrder(Order order) {
// Service에서 할 일! : Connection 객체 생성!
Connection conn = JDBCTemplate.getConnection();
// DAO 호출
// => Connection객체, Controller로부터 전달받은 무언가와 함께 같이 넘겨버리기
int result = new SubwayDao().insertOrder(conn, order);
// insert, update, delete를 하면 ~?
// 테이블의 내용물이 바뀜 => 확정(COMMIT) / 돌아가기(ROLLBACK)
if(result > 0) {
JDBCTemplate.commit(conn);
} else {
JDBCTemplate.rollback(conn);
}
// Connection 자원반납
JDBCTemplate.close(conn);
return result;
}
}
3-4. Dao
src > main(java package) > com > kh > suway > model > dao(repository) > SubwayDao.java
service에게 받은 값을 DB로 갔다가 service에게 return값 보내주기
(mapper를 통해 SQL을 파일로 받아옴)
package main.com.kh.subway.model.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import main.com.kh.subway.common.JDBCTemplate;
import main.com.kh.subway.model.vo.Order;
public class SubwayDao {
// DAO에서 항상 해야할 일!
// mapper파일 연결
// => 기본생성자 (SubwayDao가 생성될 때마다 mapper파일을 불러오게 끔)
private Properties prop = new Properties();
public SubwayDao() {
// mapper파일의 경로 담기
String fileName = SubwayDao.class.getResource("/main/sql/mapper/subway-mapper.xml").getPath();
try {
prop.loadFromXML(new FileInputStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
public int insertOrder(Connection conn, Order order) {
// INSERT! -> 처리된 행의 개수
int result = 0;
PreparedStatement pstmt = null;
String sql = prop.getProperty("insertOrder");
try {
pstmt = conn.prepareStatement(sql);
// pstmt는 항상 conn객체로 만들면서 sql문을 미리 넘김
pstmt.setString(1, order.getUserName());
pstmt.setString(2, order.getPhone());
pstmt.setString(3, order.getAddress());
pstmt.setString(4, order.getMessage());
pstmt.setString(5, order.getSandwich());
pstmt.setString(6, order.getVegetable());
pstmt.setString(7, order.getSauce());
pstmt.setString(8, order.getCookie());
pstmt.setString(9, order.getPayment());
pstmt.setInt(10, order.getPrice());
// DML문은 executeUpdat() 호출
result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCTemplate.close(pstmt);
}
return result;
}
}
4. view - 결과값 출력화면
WebContent > view > result.jsp
Controller에게 받은 값으로 화면 출력
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 스크립틀릿 : 자바코드를 그대로 작성(세미콜론을 포함한 완전한 형태로)
// 포장풀기 : request의 Attribute영역
// request.getAttribute("키값"); : Object
String sandwich = (String)request.getAttribute("sandwich");
String[] vegetable = (String[])request.getAttribute("vegetable");
String[] sauce = (String[])request.getAttribute("sauce");
String[] cookie = (String[])request.getAttribute("cookie");
String payment = (String)request.getAttribute("payment");
int price = (int)request.getAttribute("price");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>주문내역</h1>
<!-- = : 출력식, 표현식 => JSP화면에 뿌려주는 역할
=> 내가 출력할 변수명, 메소드명() 호출 => 세미콜론X -->
샌드위치 : <%= sandwich %>
채소 :
<% if(vegetable == null) { %>
선택 안 함
<% } else {%>
<%= String.join(",", vegetable) %>
<% } %>
소스 :
<% if(sauce == null) { %>
선택 안 함
<% } else {%>
<%= String.join(",", sauce) %>
<% } %>
쿠키 :
<% if(cookie == null) { %>
선택 안 함
<% } else {%>
<%= String.join(",", cookie) %>
<% } %>
결제 방식 : <%= payment %> <br><br>
위와 같이 주문하시겠습니까? <br>
총 가격 : <%= price %>원
</body>
</html>
-------------------- 주문완료 -------------------
49-2.
---------------주문한 내역 ---------------------
도 똑같이 해주면 된다.
1. Controller (Servlet)
src > main(java package) > com > kh > suway > controller > SubwayOrderController.java(Servlet)
2. -> Service
src > main(java package) > com > kh > suway > model > service > SubwayService.java
public ArrayList<Order> selectOrderList() {
// Service => Connection객체 만들기
Connection conn = JDBCTemplate.getConnection();
ArrayList<Order> list = new SubwayDao().selectOrderList(conn);
JDBCTemplate.close(conn);
return list;
}
3. -> DAO
src > main(java package) > com > kh > suway > model > dao(repository) > SubwayDao.java
public ArrayList<Order> selectOrderList(Connection conn) {
// SELECT => RESULTSET => 여러 행(ArrayList, while문)
// 필요한 변수 세팅
ArrayList<Order> list = new ArrayList();
PreparedStatement pstmt = null;
ResultSet rset = null;
String sql = prop.getProperty("selectOrderList");
try {
pstmt = conn.prepareStatement(sql);
pstmt.executeQuery();
while(rset.next()) {
Order order = new Order(rset.getString("USER_NAME"),
rset.getString("PHONE"),
rset.getString("ADDRESS"),
rset.getString("MESSAGE"),
rset.getString("SANDWICH"),
rset.getString("VEGETABLE"),
rset.getString("SAUCE"),
rset.getString("COOKIE"),
rset.getString("PAYMENT"),
rset.getInt("PRICE"),
rset.getDate("ORDER_DATE"));
list.add(order);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCTemplate.close(rset);
JDBCTemplate.close(pstmt);
}
return list;
}
4. Mapper에 SQL문
<entry key="selectOrderList">
SELECT
USER_NAME,
PHONE,
ADDRESS,
MESSAGE,
SANDWICH,
VEGETABLE,
SAUCE,
COOKIE,
PAYMENT,
PRICE,
ORDER_DATE
FROM
TB_ORDER
ORDER
BY
ORDER_DATE DESC
</entry>
5. View
WebContent > view > orderList.jsp
Controller에서 만들어줘도 되지만 View로 JSP파일을 하나 만들어 화면에 나타내 준다
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.util.ArrayList, main.com.kh.subway.model.vo.Order" %>
<%
// .getAttribute("키값") : Object
String alertMsg = (String)request.getAttribute("alertMsg");
ArrayList<Order> list = (ArrayList<Order>)request.getAttribute("list");
// java.util.ArrayList.ArrayList<Order> list = (ArrayList<Order>)request.getAttribute("list"); // import안하고 이렇게 쓸 수도 있음
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>샌드위치 주문내역 확인</h2>
<table border="1">
<tr>
<th>주문자명</th>
<th>핸드폰번호</th>
<th>주소</th>
<th>요청사항</th>
<th>샌드위치</th>
<th>채소</th>
<th>소스</th>
<th>쿠키</th>
<th>결제수단</th>
<th>총금액</th>
<th>주문일자</th>
</tr>
<% if(list.isEmpty()) { %>
<tr>
<td colspan="11"><%= alertMsg %></td>
</tr>
<% } else { %>
<!-- 조회결과가 있음!! -->
<!-- 리스트에 반복을 돌리면서 요소들에 순차적으로 접근해서 HTML요소를 생성-->
<% for(Order o : list) { %>
<tr>
<td><%= o.getUserName() %></td>
<td><%= o.getPhone() %></td>
<td><%= o.getAddress() %></td>
<td><%= o.getMessage() %></td>
<td><%= o.getSandwich() %></td>
<td><%= o.getVegetable() %></td>
<td><%= o.getSauce() %></td>
<td><%= o.getCookie() %></td>
<td><%= o.getPayment() %></td>
<td><%= o.getPrice() %></td>
<td><%= o.getOrderDate() %></td>
</tr>
<% } %>
<% } %>
</table>
</body>
</html>
Controller - Servlet (.java)
View - JSP File (.jsp)
나머지 - Java File (.java)
**** classes는 컴파일된 파일이 들어가니까 절대!!! 건드리지 말것!!!!
'WAS > WAS수업' 카테고리의 다른 글
#52. DB 테이블 설계, JSP/Servlet 회원(로그아웃, 회원가입) (0) | 2023.09.13 |
---|---|
#50. JSP/Servlet 회원(로그인) (0) | 2023.09.11 |
#48. Servlet (POST방식) / JSP / error시 띄어줄 페이지만들기 (0) | 2023.09.07 |
#47. Servlet (Get방식) (1) | 2023.09.06 |