2. Controller ① 데이터 소스, dao 를 module(coupon_insert()로 넘김) 에 넘김
-> DB정보 및 setter 값을 받아서 insert 실행
@Controller
public class shop_main {
@Autowired
BasicDataSource datasource; //얘도 클래스
PrintWriter pw = null;
@RequestMapping(value="/coupon_writeok.do",method=RequestMethod.POST)
//void : view 페이지 안쓰겠다는 것 ->Httpservletresponse 써야 printwrite 찍을 수 있음
public void coupon_writeok(@ModelAttribute("coupon") coupon_dao dao,
HttpServletResponse res) throws Exception{
res.setContentType("text/html;charset=utf-8");
//데이터 소스 전체를 넘김
//Module 에서 데이터를 insert 시키며 결과값을 return 받아서 처리
coupon_insert ci = new coupon_insert();
//데이터 베이스 정보, dao 정보를 인자값으로 이관
String callback = ci.result(datasource,dao); //어차피 coupon_insert()부터 실행돼서 받아오기떄문에 null로던져도 됨
this.pw = res.getWriter();
//결과 값에 맞는 조건식
if(callback=="Y") { //equals 쓰면 오류남
this.pw.write("<script>"
+ "alert('정상적으로 쿠폰이 등록 되었습니다.');"
+ "location.href='./coupon_list.do';"
+ "</script>");
}else {
this.pw.write("<script>"
+ "alert('데이터 오류로 인하여 쿠폰이 등록되지 않았습니다.');"
+ "history.go(-1);"
+ "</script>");
}
}
}
3. Module 3-1. DAO 제작 -> 컬럼명과 동일하게 변수 제작
@Getter
@Setter
public class coupon_dao {
int cidx, cprate;
String cpname, cpuse, cpdate, indate;
}
3-2. 쿠폰 insert 파트
public class coupon_insert {
Connection con = null;
PreparedStatement ps = null;
String rs = ""; //결과 값을 리턴하는 변수
//DB정보 및 setter 값을 받아서 insert 실행
public String result (BasicDataSource datasource,coupon_dao dao) {
try {
this.con = datasource.getConnection();
String sql = "insert into coupon values('0',?,?,?,?,now())";
this.ps = this.con.prepareStatement(sql);
this.ps.setString(1, dao.getCpname());
this.ps.setInt(2, dao.getCprate());
this.ps.setString(3, dao.getCpuse());
this.ps.setString(4, dao.getCpdate());
this.ps.executeUpdate();
this.rs ="Y"; //승인 확정
this.ps.close();
this.con.close();
} catch (Exception e) {
this.rs = "N"; //오류 발생
}
return rs; //결과 값을 리턴
}
}
2-3. 쿠폰 리스트 출력
1. View
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="cp" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠폰 리스트</title>
</head>
<body>
<p>쿠폰 등록 총 데이터 : ${ctn}EA</p>
<table border="1" cellpading="0" cellspacing="0">
<thead>
<tr>
<th>번호</th>
<th>쿠폰명</th>
<th>할인율</th>
<th>사용 유/무</th>
<th>수정/삭제</th>
</tr>
</thead>
<tbody>
<!-- varStatus = status : forEach 에 대한 정보값을 설정하는 코드
- .index : 노드번호 0부터 시작
- .count : 1부터 시작하는 번호
- .last : 맨 마지막 번호값 (true : 마지막 데이터일경우 / false : 다음 데이터가 있는 상황)
(속성값이 필요함)
- .begin : 시작번호
- .end : 종료 번호
- .step : 증가값
-->
<form id="frm" method="post" action="./coupon_del_list.do">
<input type="hidden" name="arr">
<cp:forEach var="cpdata" items="${all_list}" varStatus="status">
<tr>
<td><!--${ctn - status.index}-->
<input type="checkbox" id="del_list" name="del_list" value="${cpdata.get(0)}">
</td>
<td>${cpdata.get(1)}</td>
<td>${cpdata.get(2)}</td>
<td>${cpdata.get(3)}</td>
<td>
<input type="button" value="수정" onclick="coupon_modify('${cpdata.get(0)}')">
<input type="button" value="삭제" onclick="coupon_del('${cpdata.get(0)}')">
</td>
</tr>
</cp:forEach>
</form>
</tbody>
</table>
<input type="button" value="선택 삭제" onclick="choice_del()">
</body>
<script>
function choice_del() {
const arr = [];
const no = document.getElementsByName("del_list");
for (let i = 0; i < del_list.length; i++) {
// 속성중에 체크 된 항목이 있을 경우
if (del_list[i].checked == true) {
arr.push(del_list[i].value);
}
}
document.getElementsByName("arr")[0].value=arr;
frm.submit();
}
function coupon_del(no) {
if(confirm("해당 쿠폰 삭제시 복구 되지 않습니다."))
location.href='./coupon_del.do?cidx='+no;
}
function coupon_modify(no) {
location.href='./coupon_modify.do?cidx='+no;
}
</script>
</html>
2. Controller
@Controller
public class shop_main {
@Autowired
BasicDataSource datasource; //얘도 클래스
PrintWriter pw = null;
Connection con = null; //원래는 모듈에 들어가야함
PreparedStatement ps = null;
ResultSet rs = null;
//쿠폰 리스트 (M:dao, C:coupon_list V:jsp)
@GetMapping("/coupon_list.do")
public String coupon_list(Model m) throws Exception{
try {
this.con = datasource.getConnection();
String sql = "select cidx,cpname,cprate,cpuse from coupon order by cidx desc";
this.ps = this.con.prepareStatement(sql);
this.rs = this.ps.executeQuery();
//1차배열 및 setter, getter
coupon_dao cd = new coupon_dao();
//2차배열
ArrayList<ArrayList<Object>> all = new ArrayList<ArrayList<Object>>();
int ctn = 0;
while(this.rs.next()) {
ctn = this.rs.getRow();//auto_increment와는 다른 객체
//0번이 아니라 1번부터 시작해야함
cd.setCidx(Integer.parseInt(this.rs.getString(1)));
cd.setCpname(this.rs.getString(2));
cd.setCprate(Integer.parseInt(this.rs.getString(3)));
cd.setCpuse(this.rs.getString(4));
all.add(cd.lists());
};
// VIEW 로 보냄(JSTL 로 해당 데이터를 이관)
//데이터 총 갯수
m.addAttribute("ctn",ctn);
//데이터 리스트 배열
m.addAttribute("all_list",all);
} catch (Exception e) {
System.out.println("DB연결오류발생");
}finally {
this.rs.close();
this.ps.close();
this.con.close();
}
return null;
}
3. Module -> select 에 사용할 1차 클래스 배열 생성 -> Collections.singletonList( null ) 을 통해 null 값 까지 출력되는 것을 막음
@Getter
@Setter
public class coupon_dao {
int cidx, cprate;
String cpname, cpuse, cpdate, indate;
//select에 사용할 1차 클래스 배열
public ArrayList<Object> lists(){
ArrayList<Object> al = new ArrayList<Object>();
al.add(getCidx());
al.add(getCpname());
al.add(getCprate());
al.add(getCpuse());
al.add(getCpdate());
al.add(getIndate());
//al.removeAll(Arrays.asList("",null));
al.removeAll(Collections.singletonList(null));
return al;
}
}
@Controller
public class shop_main {
@Autowired
BasicDataSource datasource; //얘도 클래스
PrintWriter pw = null;
/*select 에서만 사용함*/
Connection con = null; //원래는 모듈에 들어가야함
PreparedStatement ps = null;
ResultSet rs = null;
//쿠폰 수정 버튼
@RequestMapping("/coupon_modifyok.do")
public String coupon_modifyok(@ModelAttribute("cp") coupon_dao dao,
HttpServletResponse res,Model m) throws IOException {
res.setContentType("text/html;charset=utf-8");
coupon_update cu = new coupon_update();
String callback = cu.modifyok(datasource,dao);
this.pw = res.getWriter();
//결과 값에 맞는 조건식
if(callback=="Y") { //equals 쓰면 오류남
this.pw.write("<script>"
+ "alert('정상적으로 쿠폰이 수정 되었습니다..');"
+ "location.href='./coupon_list.do';"
+ "</script>");
m.addAttribute("md_info", dao.lists());
}else {
this.pw.write("<script>"
+ "alert('데이터 오류로 인하여 쿠폰이 등록되지 않았습니다.');"
+ "history.go(-1);"
+ "</script>");
}
return null;
}
//쿠폰 정보 수정 페이지
@GetMapping ("/coupon_modify.do")
String coupon_modify(int cidx,coupon_dao dao, Model m) throws Exception {
coupon_update cu = new coupon_update();
//DB정보, dao, db고유값 해당 메소드로 전달 (Setter로 이용하기 위해서)
cu.select_one(datasource, dao, cidx);
//최종값은 getter값을 배열로 제작 후 view(jstl) 형태로 이관
m.addAttribute("info",dao.lists());
return null;
}
3. Module ⑴ 쿠폰 수정 모듈 - modifyok 메소드 ⑵ 쿠폰 수정 페이지 출력 모듈 - select_one 메소드
public class coupon_update {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
public void select_one(BasicDataSource dataSource, coupon_dao dao, int cidx) throws Exception{
try {
String sql = "select * from coupon where cidx=?";
this.con = dataSource.getConnection();
this.ps = this.con.prepareStatement(sql);
this.ps.setInt(1, cidx);
this.rs = this.ps.executeQuery();
this.rs.next();
//database의 하나의 row 값을 dao 의 setter 메소드에 값을 이관 시킴
dao.setCidx(Integer.parseInt(this.rs.getString(1)));
dao.setCpname(this.rs.getString(2));
dao.setCprate(Integer.parseInt(this.rs.getString(3)));
dao.setCpuse(this.rs.getString(4));
dao.setCpdate(this.rs.getString(5));
dao.setIndate(this.rs.getString(6));
}catch (Exception e) {
System.out.println("error");
}finally {
this.rs.close();
this.ps.close();
}
}
String result="";
//쿠폰 수정
public String modifyok(BasicDataSource datasource, coupon_dao dao) {
try {
this.con = datasource.getConnection();
String sql = "update coupon set cpname=?, cprate=?, cpuse=?,cpdate=?,indate=? where cidx=?";
this.ps = this.con.prepareStatement(sql);
this.ps.setString(1, dao.getCpname());
this.ps.setInt(2, dao.getCprate());
this.ps.setString(3, dao.getCpuse());
this.ps.setString(4, dao.getCpdate());
this.ps.setString(5, dao.getIndate());
this.ps.setInt(6, dao.getCidx());
this.ps.executeUpdate();
this.result="Y";
} catch (Exception e) {
e.printStackTrace();
this.result="N";
System.out.println("에러");
}
return this.result;
}
}
2-5. 쿠폰 삭제
1.Module ⑴ del_result 메소드 : 결과 값을 리턴 받는 string 메소드
public class coupon_insert {
Connection con = null;
PreparedStatement ps = null;
String rs = ""; //결과 값을 리턴하는 변수
public String del_result(BasicDataSource datasource , int cidx) throws SQLException {
try {
this.con = datasource.getConnection();
String sql = "delete from coupon where cidx=?";
this.ps = this.con.prepareStatement(sql);
this.ps.setInt(1, cidx);
this.ps.executeUpdate();
this.rs = "Y";
} catch (Exception e) {
e.printStackTrace();
System.out.println("db 쿼리문 오류 발생");
this.rs = "N";
}finally {
this.ps.close();
this.con.close();
}
return this.rs;
}
2.View -> 리스트 출력 파트 view 를 그대로사용 (받아오는 부분만 올려둠) 체크박스로 선택해서 삭제 할 항목 여러개 체크 할 수 있게끔 제작체크한 항목을 검사해서 보내는 choice_del()함수와 idx값만 get으로 보내는 coupon_del()함수 3.Controller ⑴ 쿠폰 단일 삭제 -> view page 필요없어서 void로 씀 -> 쿠폰의 idx 값을 받아와서 처리 (get으로 넘겨받음)
⑵ 쿠폰 여러개 체크박스 선택 후 삭제 -> 삭제 할 쿠폰 idx값을 배열로 받아와서 모듈로 넘김
@Controller
public class shop_main {
@Autowired
BasicDataSource datasource; //얘도 클래스
PrintWriter pw = null;
@RequestMapping(value="/coupon_del_list.do",method=RequestMethod.POST)
public void coupon_del_list(String arr, int del_list, HttpServletResponse res) throws Exception {
res.setContentType("text/html;charset=utf-8");
String[] data = arr.split(",");
ArrayList<String> al = new ArrayList<String>(Arrays.asList(data));
String callback="Y";
int w=0;
while(w<al.size()) {
String callback_2 = new coupon_insert().del_result(datasource, Integer.parseInt(al.get(w)));
if(callback_2=="N") {
callback="N";
}
w++;
}
this.pw = res.getWriter();
if(callback == "Y") {
this.pw.write("<script>"
+ "alert('정상적으로 쿠폰이 삭제 되었습니다.');"
+ "location.href='./coupon_list.do';"
+ "</script>");
}else {
this.pw.write("<script>"
+ "alert('데이터 오류로 인하여 쿠폰이 삭제되지 않았습니다.');"
+ "location.href='./coupon_list.do';"
+ "</script>");
}
this.pw.close();
}
1. dao 생성 (coupon_dao.java)
⑴ 컬럼명과 동일하게 변수 생성 ⑵ 쿠폰 리스트 Module - select 에 사용할 1차 클래스 배열 생성 ① Collections.singletonList(null) 을 통해 null 값 까지 출력되는 것을 막음 - 코드 예시 )
@Setter
@Getter
public class member_dao {
int uidx;
String uid,upass,uname,ujoin;
//select에 사용할 1차 클래스 배열
public ArrayList<Object> lists(){
ArrayList<Object> al = new ArrayList<Object>();
al.add(getCidx());
al.add(getCpname());
al.add(getCprate());
al.add(getCpuse());
al.add(getCpdate());
al.add(getIndate());
al.removeAll(Collections.singletonList(null));
return al;
}
}
2. Controller (shop_main.java)
⑴ 쿠폰 생성 Controller
① 데이터 소스, dao 를 module(coupon_insert()로 넘김) 에 넘김
② 모듈클래스 coupon_insert의 result 메소드를 로드해서 데이터소스를 넘겨서 결과 값( callback )을 리턴받아옴
⑵ 쿠폰 리스트 Controller
① 리스트에 필요한 컬럼만 가져오면 되므로 알맞은 쿼리문 작성 -> ex ) select cidx,cpname,cprate,cpuse from coupon order by cidx desc
② 모듈에서 1차배열로 받은 데이터를 2차배열로 다시 받아옴 (가져올 때 getString 은 1번부터 시작함) -> 쿠폰 별로 쿠폰 정보를 다 긁어오기 위함 -> 긁어온 데이터를 jstl로 coupon_list.jsp 에 출력하기 위해 coupon_list 의 인자값을 Model 자료형으로 함
- 코드 예시 )
@Controller
public class shop_main {
@Autowired
BasicDataSource datasource; //얘도 클래스
PrintWriter pw = null;
/*select 에서만 사용함*/
Connection con = null; //원래는 모듈에 들어가야함
PreparedStatement ps = null;
ResultSet rs = null;
//쿠폰 리스트 (M:dao, C:coupon_list V:jsp)
@GetMapping("/coupon_list.do")
public String coupon_list(Model m) throws Exception{
try {
this.con = datasource.getConnection();
String sql = "select cidx,cpname,cprate,cpuse from coupon order by cidx desc";
this.ps = this.con.prepareStatement(sql);
this.rs = this.ps.executeQuery();
//1차배열 및 setter, getter
coupon_dao cd = new coupon_dao();
//2차배열
ArrayList<ArrayList<Object>> all = new ArrayList<ArrayList<Object>>();
int ctn = 0;
while(this.rs.next()) {
ctn = this.rs.getRow();//auto_increment와는 다른 객체
cd.setCidx(Integer.parseInt(this.rs.getString(1))); //0번이 아니라 1번부터 시작해야함
cd.setCpname(this.rs.getString(2));
cd.setCprate(Integer.parseInt(this.rs.getString(3)));
cd.setCpuse(this.rs.getString(4));
all.add(cd.lists());
};
// VIEW 로 보냄(JSTL 로 해당 데이터를 이관)
//데이터 총 갯수
m.addAttribute("ctn",ctn);
//데이터 리스트 배열
m.addAttribute("all_list",all);
} catch (Exception e) {
System.out.println("DB연결오류발생");
}finally {
this.rs.close();
this.ps.close();
this.con.close();
}
return null;
}
@RequestMapping(value="/coupon_writeok.do",method=RequestMethod.POST)
//void : view 페이지 안쓰겠다는 것 ->Httpservletresponse 써야 printwrite 찍을 수 있음
public void coupon_writeok(@ModelAttribute("coupon") coupon_dao dao,
HttpServletResponse res)throws Exception{
res.setContentType("text/html;charset=utf-8");
//데이터 소스 전체를 넘김 ,
coupon_insert ci = new coupon_insert();
String callback = ci.result(datasource,dao);
this.pw = res.getWriter();
if(callback=="Y") { //equals 쓰면 오류남
this.pw.write("<script>"
+ "alert('정상적으로 쿠폰이 등록 되었습니다.');"
+ "location.href='./coupon_list.do';"
+ "</script>");
}else {
this.pw.write("<script>"
+ "alert('데이터 오류로 인하여 쿠폰이 등록되지 않았습니다.');"
+ "history.go(-1);"
+ "</script>");
}
}
}
3. Module ( coupon_insert.java -> 실무에서는 coupon_ddl 등 으로 생성함:쿼리문 다들어가도록)
⑴ 쿠폰 생성 module - controller 에서 던진 DB정보 및 setter 값을 받아서 insert 실행 인자 받는 파트 상세 ⑵ 쿠폰 삭제 module
- 코드 예시 )
public class coupon_insert {
Connection con = null;
PreparedStatement ps = null;
String rs = ""; //결과 값을 리턴하는 변수
//DB정보 및 setter 값을 받아서 insert 실행
public String result (BasicDataSource datasource,coupon_dao dao) {
try {
this.con = datasource.getConnection();
String sql = "insert into coupon values('0',?,?,?,?,now())";
this.ps = this.con.prepareStatement(sql);
this.ps.setString(1, dao.getCpname());
this.ps.setInt(2, dao.getCprate());
this.ps.setString(3, dao.getCpuse());
this.ps.setString(4, dao.getCpdate());
this.ps.executeUpdate();
this.rs ="Y"; //승인 확정
this.ps.close();
this.con.close();
} catch (Exception e) {
this.rs = "N"; //오류 발생
}
return rs; //결과 값을 리턴
}
}
4. 쿠폰리스트 출력 ( View )
⑴ controller 에서 받은 데이터( 2차배열 ) JSTL로 출력
⑵ varStatus = "status" 속성 사용법 : forEach 에 대한 정보값을 설정하는 코드 ① .index : 노드번호 0부터 시작 ② .count : 1부터 시작하는 번호 ③ .last : 맨 마지막 번호값 (true : 마지막 데이터일경우 / false : 다음 데이터가 있는 상황) ④ .begin : 시작번호 ⑤ .end : 종료 번호 ⑥ .step : 증가값
⑶ 코드 예시 ) ① coupon_lis.jsp (View) 출력 되는 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="cp" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠폰 리스트</title>
</head>
<body>
<p>쿠폰 등록 총 데이터 : ${ctn}EA</p>
<table border="1" cellpading="0" cellspacing="0">
<thead>
<tr>
<th>번호</th>
<th>쿠폰명</th>
<th>할인율</th>
<th>사용 유/무</th>
<th>수정/삭제</th>
</tr>
</thead>
<tbody>
<form id="frm" method="post" action="./coupon_del_list.do">
<input type="hidden" name="arr">
<cp:forEach var="cpdata" items="${all_list}" varStatus="status">
<tr>
<td><!--${ctn - status.index}-->
<input type="checkbox" id="del_list" name="del_list" value="${cpdata.get(0)}">
</td>
<td>${cpdata.get(1)}</td>
<td>${cpdata.get(2)}</td>
<td>${cpdata.get(3)}</td>
<td>
<input type="button" value="수정" onclick="coupon_modify('${cpdata.get(0)}')">
<input type="button" value="삭제" onclick="coupon_del('${cpdata.get(0)}')">
</td>
</tr>
</cp:forEach>
</form>
</tbody>
</table>
<input type="button" value="선택 삭제" onclick="choice_del()">
</body>
<script>
function choice_del() {
const arr = [];
const no = document.getElementsByName("del_list");
for (let i = 0; i < del_list.length; i++) {
// 속성중에 체크 된 항목이 있을 경우
if (del_list[i].checked == true) {
arr.push(del_list[i].value);
}
}
document.getElementsByName("arr")[0].value=arr;
frm.submit();
}
function coupon_del(no) {
if(confirm("해당 쿠폰 삭제시 복구 되지 않습니다."))
location.href='./coupon_del.do?cidx='+no;
}
function coupon_modify(no) {
location.href='./coupon_modify.do?cidx='+no;
}
</script>
</html>
② 출력 시키는 Module (coupon_dao.java) -> jstl 로 리스트를 띄우기 위해 데이터를 클래스 배열에 담아서 jsp 로 이관
@Getter
@Setter
public class coupon_dao {
int cidx, cprate;
String cpname, cpuse, cpdate, indate;
//select에 사용할 1차 클래스 배열
public ArrayList<Object> lists(){
ArrayList<Object> al = new ArrayList<Object>();
al.add(getCidx());
al.add(getCpname());
al.add(getCprate());
al.add(getCpuse());
al.add(getCpdate());
al.add(getIndate());
//al.removeAll(Arrays.asList("",null));
al.removeAll(Collections.singletonList(null));
return al;
}
}
③ 쿠폰 리스트 출력 Controller 파트
@GetMapping("/coupon_list.do")
public String coupon_list(Model m) throws Exception{
try {
this.con = datasource.getConnection();
String sql = "select cidx,cpname,cprate,cpuse from coupon order by cidx desc";
this.ps = this.con.prepareStatement(sql);
this.rs = this.ps.executeQuery();
//1차배열 및 setter, getter
coupon_dao cd = new coupon_dao();
//2차배열
ArrayList<ArrayList<Object>> all = new ArrayList<ArrayList<Object>>();
int ctn = 0;
while(this.rs.next()) {
ctn = this.rs.getRow();//auto_increment와는 다른 객체
//0번이 아니라 1번부터 시작해야함
cd.setCidx(Integer.parseInt(this.rs.getString(1)));
cd.setCpname(this.rs.getString(2));
cd.setCprate(Integer.parseInt(this.rs.getString(3)));
cd.setCpuse(this.rs.getString(4));
all.add(cd.lists());
};
// VIEW 로 보냄(JSTL 로 해당 데이터를 이관)
//데이터 총 갯수
m.addAttribute("ctn",ctn);
//데이터 리스트 배열
m.addAttribute("all_list",all);
} catch (Exception e) {
System.out.println("DB연결오류발생");
}finally {
this.rs.close();
this.ps.close();
this.con.close();
}
return null;
}