coupon.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠폰 등록 페이지</title>
</head>
<body>
<form id="frm" method="post" action="./coupon_part2.do">
<p>쿠폰 등록 페이지</p>
아이디 : <input type="text" name="mid"><br>
쿠폰 번호 : <input type="text" name="cnum"><br>
<input type="checkbox" name="agree_ad">광고 수신 동의(필수)<br>
<input type="button" value="쿠폰 등록" onclick="couponok()">
</form>
</body>
<script>
var couponok = function(){
if(frm.mid.value==""){
alert("아이디를 입력하세요!");
frm.mid.focus();
} else if(frm.cnum.value==""){
alert("쿠폰 번호를 입력하세요!");
frm.cnum.focus();
} else if(!frm.agree_ad.checked){
alert("광고 수신 동의를 체크해주세요!");
frm.agree_ad.focus();
} else{
frm.submit();
}
}
</script>
</html>
coupon_part2.java (servlet)
package review;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class coupon_part2 extends HttpServlet {
private static final long serialVersionUID = 1L;
PrintWriter pw = null;
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
res.setContentType("text/html;charset=utf-8");
try {
this.pw = res.getWriter();
String mid = req.getParameter("mid");
String cnum = req.getParameter("cnum");
String agree_ad = req.getParameter("agree_ad");
String ca[] = {"A1316B1004", "C4024A0096", "B1987C3136"};
ArrayList<String> clist = new ArrayList<String>(Arrays.asList(ca));
ArrayList<String> data = new ArrayList<String>();
//System.out.println(agree_ad);
if(agree_ad.equals("on")) { //광고수신 동의일때
if(clist.contains(cnum)) { //쿠폰이 있을때
//보내기
data.add(mid);
data.add(cnum);
data.add(agree_ad);
req.setAttribute("data", data);
RequestDispatcher rd = req.getRequestDispatcher("./coupon_part2.jsp");
rd.forward(req, res);
}else { //쿠폰없을때
this.pw.write("<script>"
+ "alert('해당 쿠폰번호를 확인하세요');"
+ "history.go(-1);"
+ "</script>");
}
}else {//광고수신미동의
this.pw.write("<script>"
+ "alert('광고수신동의 오류');"
+ "history.go(-1);"
+ "</script>");
}
}catch (Exception e) {
this.pw.write("<script>"
+ "alert('올바른 접근방식이 아닙니다.');"
+ "history.go(-1);"
+ "</script>");
}finally {
this.pw.close();
}
}
}
coupon_part2.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
ArrayList<String> data = (ArrayList)request.getAttribute("data");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>쿠폰 등록 완료 페이지</title>
</head>
<body>
<p>쿠폰 등록 페이지</p>
아이디 : <%=data.get(0)%><br>
쿠폰 번호 : <%=data.get(1)%><br>
<%
if(data.get(2).equals("on")){
%>
광고 수신 동의<br>
<%
}else{
%>
<script>
alert('올바르지않은 접근입니다.');
location.href='./coupon.html';
</script>
<%
}
%>
</body>
</html>
⭐️
- 클래스 배열
- contains() : 해당 클래스 배열 안에 같은 값이 들어있는지 확인 => boolean