728x90
수업내용
1교시 (09:30-10:20)
- 지난 시간 복습
- selector_3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#select_1').change(function(){
var v = [0, 1, 2];
v[0] = ["양천구","강서구","금천구"];
v[1] = ["안양시","부천시","성남시","구리시"];
v[2] = ["부평구","연수구","강화군","계양구"];
alert("select_1 >>> : ");
var changeItem;
var slen = $(".select_1 option").length;
var slen_Val = $(".select_1 option:selected").val();
alert("slen_Val >>> : " + slen + " : " + slen_Val);
var slen_text = $(".select_1 option:selected").text();
alert("slen_text >>> : " + slen + " : " + slen_text);
// selectbox.selectIndex
});
});
</script>
</head>
<body>
<select class="select_1" name="select_1" id="select_1" style="width:150px">
<option value="0">서울</option>
<option value="1">경기도</option>
<option value="2">인천</option>
</select>
<select class="select_2" name="select_2" id="select_2" style="width:150px">
</select>
<select class="select_3" name="select_3" id="select_3" style="width:150px">
</select>
</body>
</html>
- prop_2.html ← this 키워드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
// 성별
var gen = '02';
console.log("gen >>> : " + gen);
$(".mgender").each(function(){
if ($(this).val() == gen){
$(this).prop('checked', true);
}
});
/*
if ('01' == gen) {
$(".mgender:input[value='01']").prop('checked', true);
}
if ('02' == gen) {
$(".mgencer:input[value='02']").prop('checked', true);
}
*/
// 이메일
var email = 'abc@gmail.com';
var emails = email.split('@');
$("#memail").val(emails[0]);
$("#memail1").val(emails[1]);
// 취미
var hobs = '01';
console.log("hobs >>> : " + hobs);
var hob = hobs.splot(',');
for (m=0; m < hob.length; m++) {
$(".mhobby").each(function(){
if ($(this).val() == hob[m]){
$(this).prop('checked', true);
}
});
}
/*
$(".mhobby").each(function(index){
var hobValue = hob[index];
if ('01' == hobValue){
$(".mhobby:input[value='01']").prop('checked', true);
}
if ('02' == hobValue){
$(".mhobby:input[value='02']").prop('checked', true);
}
if ('03' == hobValue){
$(".mhobby:input[value='03']").prop('checked', true);
}
if ('04' == hobValue){
$(".mhobby:input[value='04']").prop('checked', true);
}
if ('05' == hobValue){
$(".mhobby:input[value='05']").prop('checked', true);
}
});
for (var m=0; m < hob.length; m++){
var hobValue = hob[m];
console.log("hobValue >>> : " + hobValue);
if ('01' == hobValue){
$(".mhobby:input[value='01']").prop('checked', true);
}
if ('02' == hobValue){
$(".mhobby:input[value='02']").prop('checked', true);
}
if ('03' == hobValue){
$(".mhobby:input[value='03']").prop('checked', true);
}
if ('04' == hobValue){
$(".mhobby:input[value='04']").prop('checked', true);
}
if ('05' == hobValue){
$(".mhobby:input[value='05']").prop('checked', true);
}
}
*/
// 이메일 선택
$("#memail2").change(function(){
$("#memail2 option: selected").each(function(){
if ($(this).val()=='1'){ // 직접 입력일 경우
var aa = $("#memail").val();
// alert("aa >>> : " + aa);
$("#memail1").val(''); // 값 초기화
$("#memail1").prop("readonly", false); 활성화
} else { // 직접 입력이 아닐 경우
$("#memail1").val($(this).text()); // 선택값 입력
$("#memail1").prop("readonly", true); // 비활성화
}
});
});
});
</script>
</head>
<body>
<hr>
<div>
<form name="memUpdateForm" id="memUpdateForm">
<table border="1">
<script>
function compCheck(){
console.log("compCheck >>> 진입 >>> : ");
// 성별
var gen = '01';
console.log("gen >>> : " + gen);
if ('01' == gen) {
document.getElementsByName("mgender")[0].checked = true;
}
if ('02' == gen) {
document.getElementsByName("mgender")[1].checked = true;
}
// 이메일
var email = 'abc@gmail.com';
var emails = email.split('@');
document.getElementById("memail").value = emails[0];
document.getElementById("memeail1").value = emails[1];
// 취미
var hobs = '<%= mhobby %>;'
console.log("hobs >>> : " + hobs);
var hob = hobs.split(',');
for (m=0; m < hob.length; m++) {
var hobValue = hob[m];
console.log("hobValue >>> : " + hobValue);
if ('01' == hobValue) {
document.getElementsByName("mhobby")[0].checked = true;
}
if ('02' == hobValue) {
document.getElementsByName("mhobby")[1].checked = true;
}
if ('03' == hobValue) {
document.getElementsByName("mhobby")[2].checked = true;
}
if ('04' == hobValue) {
document.getElementsByName("mhobby")[3].checked = true;
}
if ('05' == hobValue) {
document.getElementsByName("mhobby")[4].checked = true;
}
}
}
</script>
<tr>
<td colspan="3" align="center">
<font size="4" style="color:blue;">회원정보 수정 & 삭제</font>
</td>
</tr>
<tr>
<td>성별</td>
<td>
<input type="radio" class="mgender" name="mgender" id="mgender" value="01" checked /> 여자
<input type="radio" class="mgender" name="mgender" id="mgender" value="02" /> 남자
</td>
</tr>
<tr>
<td>이메일</td>
<td colspan="2">
<input type="text" name="memail" id="memail" style="width:100px" />
@ <input type="text" name="memail1" id="memail1" style="width:100px"
placeholder="직접입력" />
<select name="memail2" id="memail2">
<option value="1" selected>직접입력</option>
<option value="naver.com">naver.com</option>
<option value="gmail.com">gmail.com</option>
<option value="daum.net">daum.net</option>
</select>
</td>
</tr>
<tr>
<td>취미</td>
<td colspan="2">
<input type="checkbox" class="mhobby" name="mhobby" id="mhobby" value="01" />알고리즘
<input type="checkbox" class="mhobby" name="mhobby" id="mhobby" value="02" />코딩
<input type="checkbox" class="mhobby" name="mhobby" id="mhobby" value="03" />분석설계<br>
<input type="checkbox" class="mhobby" name="mhobby" id="mhobby" value="04" />데이터베이스
<input type="checkbox" class="mhobby" name="mhobby" id="mhobby" value="05" />스크립트
</td>
</tr>
<tr>
<td colspan="3" align="center">
<input type="button" value="수정" id='U' />
<input type="button" value="삭제" id='D' />
<input type="reset" value="취소" />
<input type="button" value="입력" id='I' />
<input type="button" value="목록" id='SALL' />
</td>
<tr>
</table>
</form>
</div>
</body>
</html>
2교시 (10:30-11:20)
- 파일 업로드
-----------------
1. 파일
파일이름
-------------
-------------
파일 바이러니
2. 파일을 이동 하려면 : copy & move
Stream IO 를 이용해야 한다.
문서 파일
이미지 파일
동영상 파일
음성 파일 ....
스트리밍 서비스
3. jsp 기술로 데이터를 이동
text 데이터 이동 : request.getParameter()
file 데이터 이동 : <input type="file"
IO 를 이용해서 스트림을 처리해야 한다.
파일 업로드 컴포넌트를 사용해서 한다.
우리가 공부할 때 file 데이터 이동은
이미지
파일 업로드로 파일을 서버의 디렉토리에 저장하고
업로드된 파일의 파일명을 데이터베이스에 저장해서
사용을 한다.
파일 데이터를 관계형 데이터베이스에 저장해서 사용하는 기술
데이터베이스 CLOB, BLOB
SQL : 콜러블스테이트먼트 : CallableStatement
4. 자바 기술로 파일을 이동할 때는
파일경로, 파일 이름은 무조건 한글 사용을 지양한다.
5. FILE UPLOAD : 요청
method : POST
enctype : multipart/form-data
파일업로드 컴포넌트 :
1. cos.jar
2. commons-fileupload-1.2.1.jar
commons-io-1.4.jar
3. @MultipartConfig 어노테이션
Content-Type
media-type : 리소스 혹은 데이터의 MIME type.
charset : 문자 인코딩 표준.
boundary : 메시지의 멀티 파트 경계선을 캡슐화하기 위해
6. cos.jar 사용법
1. method : POST
enctype : multipart/form-data
2. 파일 저장소
상수로 사용하기
public static final String TEST_IMG_UPLOAD_PATH = "C:\\00.KOSMO108\\30.Web\\eclipse_work_hbe_work\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\kosMember\\upload\\aaaa";
3. MultipartRquest 생성자 인스턴스가 되면 이때 파일이 업로드가 완료 된 것이다.
이후 부터는
MultipartRquest 객체의 참조변수로 사용한다.
3교시 (11:30-12:20)
- 메일 보내기
----------------------------
SMTP 프로토콜 Simple Mail Transfer Protocol
인터넷 상에서 이메일을 전송하기 위해서 사용되는 통신 규약
SMTP 서버
이메일을 송수신하는 서버
JavaMail 라이브러리
https://mvnrepository.com/artifact/javax.mail/mail/1.4.7
HTTP
Hyper Text Transfer Protocol
클라이언트와 서버 사이에 요청/응답 request/response 프로토콜
주로 일반 텍스트로 이루어진 HTML 문서를 주고 받음
HTTPS
Hyper Text Transfer Protocol over Secure Socket Layer
소켓 통신에서 일반 텍스트를 이용하며,
SSL이나 TLS 프로토콜을 통해 세션 데이터를 암호화 함
SSL
Secure Socket Layer 보안 소켓 계층
데이터를 안전하게 전송하기 위한 인터넷 암호화 통신 프로토콜
전자상거래 등 보안을 위해 네스케이프 netscape에서 처음 만듦
SSL을 적용하지 않고 암호화되지 않는 데이터를 전송하면
스누핑 Snooping, 스니핑 Sniffing의 위협에 노출 됨
TLS
Transport Layer security
인터넷에서 정보를 암호화해서 송수신하는 프로토콜
SSL 기반 기술로 국제 인터넷 표준화 기구에서 표준으로 인정
SSL은 POODLE, DROWN 등의 취약점이 발견되어 현재는 사용하지 않음
다양한 종류의 보안 통신을 하기 위한 프로토콜
4교시 (12:30-13:20)
- GmailVO.java
package a.b.c.test.mail;
public class GmailVO {
private String mailsubject;
private String sendmail;
private String mailpw;
private String receivemail;
private String sendmsg;
// 생성자
public GmailVO() {
}
public GmailVO(String mailsubject, String sendmail, String mailpw, String receivemail, String sendmsg) {
super();
this.mailsubject = mailsubject;
this.sendmail = sendmail;
this.mailpw = mailpw;
this.receivemail = receivemail;
this.sendmsg = sendmsg;
}
// getter()
public String getMailsubject() {
return mailsubject;
}
public String getSendmail() {
return sendmail;
}
public String getMailpw() {
return mailpw;
}
public String getReceivemail() {
return receivemail;
}
public String getSendmsg() {
return sendmsg;
}
// setter()
public void setMailsubject(String mailsubject) {
this.mailsubject = mailsubject;
}
public void setSendmail(String sendmail) {
this.sendmail = sendmail;
}
public void setMailpw(String mailpw) {
this.mailpw = mailpw;
}
public void setReceivemail(String receivemail) {
this.receivemail = receivemail;
}
public void setSendmsg(String sendmsg) {
this.sendmsg = sendmsg;
}
}
- GmailAuth.java
package a.b.c.test.mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class GmailAuth extends Authenticator {
PasswordAuthentication pa;
public GmailAuth(GmailVO gvo) {
System.out.println("GmailAuth sendMail >>> : " + gvo.getSendmail());
System.out.println("GmailAuth sendPw >>> : " + gvo.getMailpw());
// gmail 아이디, gmail 비밀번호
pa = new PasswordAuthentication(gvo.getSendmail(), gvo.getMailpw());
}
public PasswordAuthentication getPasswordAuthenticatiobn() {
return pa;
}
}
- GmailSend.java
package a.b.c.test.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GmailSend {
public void gmailSend(GmailVO gvo) {
System.out.println("gmaillSend mailsubject >>> : " + gvo.getMailsubject());
System.out.println("gmaillSend sendmail >>> : " + gvo.getSendmail());
System.out.println("gmaillSend mailpw >>> : " + gvo.getMailpw());
System.out.println("gmaillSend getReceivemail >>> " + gvo.getReceivemail());
System.out.println("gmaillSend sendmsg >>> : " + gvo.getSendmsg());
// mail을 처리하는 환경 세팅하기
Properties prop = System.getProperties();
// 로그인시 TLS를 사용할 것인지 설정
// prop.put("mail.smtp.starttls.enable","false");
// 이메일 발송을 처리해줄 SMTP 서버
prop.put("mail.smtp.host","smtp.gmail.com");
// SMTP 서버의 인증을 사용한다는 의미
prop.put("mail.smtp.auth","true");
// TLS 포트 번호 587, SSL 포트번호 465
// prop.put("mail.smtp.port","587");
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mailsmtp.ssl.trust", "smtp.gmail.com");
prop.put("mail.smtp.starttls.required",true);
prop.put("mail.smtp.starttls.enable",true);
prop.put("mail.smtp.port",465);
// prop.put("mail.smtp.socketFactory.class",javax.net.ssl.SSLSocketFactory);
// prop.put("mail.smtp.socketFactory.fallback",true);
// prop.put("mail.smtp.socketFactory.port",465);
// gmail password check
Authenticator auth = new GmailAuth(gvo);
// GmailAuth 클래스로 사용자가 인증이되면 메일을 사용할 세션을 생성한다.
Session session = Session.getDefaultInstance(prop, auth);
// msg 메시지 객체 생성
MimeMessage msg = new MimeMessage(session);
try {
// 보내는 날짜 지정
msg.setSentDate(new Date());
// 발송자
msg.setFrom(new InternetAddress(gvo.getSendmail(), gvo.getMailsubject()));
// 수신자의 메일을 생성
// google, naver, daum 등 가능
InternetAddress to = new InternetAddress(gvo.getReceivemail());
// Message 클래스의 setRecipient() 함수를 사용하여 수신자를 설정
// setRecipient() 메소드로 수신자, 참조, 숨은참조 설정 가능
// Message.RecipientType.TO : 받는사람
// Message.RecipientType.CC : 참조
// Message.RecipientType.BCC : 숨은 참조
msg.setRecipient(Message.RecipientType.TO, to);
// 메일 제목 및 encoding 타입 설정
msg.setSubject(gvo.getMailsubject(), "UTF-8");
// 메일 내용 및 encoding 타입 설정
msg.setText(gvo.getSendmsg(), "UTF-8");
// 메일 전송
Transport.send(msg);
} catch(AddressException ae) {
System.out.println("AddressException : " + ae.getMessage());
} catch(MessagingException me) {
// 메일 계정인증 관련 에러
System.out.println("MessagingException : " + me.getMessage());
} catch(UnsupportedEncodingException e) {
// 지원되지 않는 인코딩을 사용할 경우 예외 처리
System.out.println("UnsupportedEncodingException : " + e.getMessage());
}
}
}
5교시 (14:30-15:20)
- gmail_send.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- mail 객체 import -->
<%@ page import="a.b.c.test.mail.GmailSend" %>
<%@ page import="a.b.c.test.mail.GmailVO" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GMAIL SEND</title>
</head>
<body>
<h3>GMAIL SEND</h3>
<hr>
<%
String mailsubject = request.getParameter("mailsubject");
String sendmail = request.getParameter("sendmail");
String mailpw = request.getParameter("mailpw");
String receivemail = request.getParameter("receivemail");
String sendmsg = request.getParameter("sendmsg");
System.out.println("mailsubject >>> : " + mailsubject);
System.out.println("sendmail >>> : " + sendmail);
System.out.println("mailpw >>> : " + mailpw);
System.out.println("receivemail >>> : " + receivemail);
System.out.println("sendmsg >>> : " + sendmsg);
GmailVO gvo = null;
gvo = new GmailVO();
gvo.setMailsubject(mailsubject);
gvo.setSendmail(sendmail);
gvo.setMailpw(mailpw);
gvo.setReceivemail(receivemail);
gvo.setSendmsg(sendmsg);
GmailSend gms = new GmailSend();
gms.gmailSend(gvo);
%>
</body>
</html>
- gmail_send.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GMAIL SEND</title>
<script type="text/javascript">
function sendMail(){
console.log("sendMail() 진입 >>> : ");
document.sendMailForm.action="/KosMember/kos_mail/gmail_send.jsp";
document.sendMailForm.method="POST";
document.sendMailForm.enctype="application/x-www-form-urlencoded";
document.sendMailForm.submit();
}
</script>
</head>
<body>
<h3>Google Mail Server를 사용해서 메일 보내기</h3>
<hr>
<form name="sendMailForm" id="sendMailForm">
<table border="1">
<tr>
<td> 제목 : </td>
<td><input type="text" name="mailsubject" id="mailsubject" size="50https://blog.naver.com/GoBlogWrite.naver"></td>
</tr>
<tr>
<td>보내는 메일 : </td>
<td><input type="text" name="sendmail" id="sendmail" size="50"></td>
</tr>
<tr>
<td>비밀번호 : </td>
<td><input type="password" name="mailpw" id="mailpw" size="50"></td>
</tr>
<tr>
<td>받는 메일 : </td>
<td><input type="text" name="receivemail" id="receivemail" size="50"></td>
</tr>
<tr>
<td>내용 : </td>
<td><textarea name="sendmsg" id="sendmsg" rows="5" cols="50"></textarea></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="button" value="메일 보내기" onclick="sendMail();">
<input type="reset" value="다시">
</td>
</tr>
</table>
</form>
</body>
</html>
6교시 (15:30-16:20)
- pwTempSend.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- log4 객체 import -->
<%@ page import="org.apache.log4j.LogManager" %>
<%@ page import="org.apache.log4j.Logger" %>
<!-- PasswordUtil 객체 import -->
<%@ page import="a.b.c.common.PasswordUtil" %>
<%@ page import="a.b.c.common.EncryptAES" %>
<%@ page import="a.b.c.common.EncryptSHA" %>
<!-- mail 객체 import -->
<%@ page import="a.b.c.test.mail.GmailSend" %>
<%@ page import="a.b.c.test.mail.GmailVO" %>
<!-- 커넥션 클래스 import -->
<%@ page import="a.b.c.common.KosConnectivity" %>
<!-- java.sql.* JDBC 클래스 import -->
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<!-- 깡통 클래스 import -->
<%@ page import="a.b.c.kos.mem.vo.MemVO" %>
<%@ page import="a.b.c.test.mail.TpwVO" %>
<%@ page import="java.util.ArrayList" %>
<% request.setCharacterEncoding("UTF-8"); %>
<%
Logger logger = LogManager.getLogger(this.getClass());
logger.info("pwTempSend.jsp 페이지 >>> : ");
String mhp = request.getParameter("mhp");
String memail = request.getParameter("memail");
MemVO mvo = null;
mvo = new MemVO();
mvo.setMhp(mhp);
mvo.setMemail(memail);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rsRs = null;
int nCnt = 0;
boolean bool = false;
conn = KosConnectivity.getConnection();
String sqls = "SELECT COUNT(A.MNUM) NCNT FROM KOS_MEMBER A WHERE A.DELETEYN='Y' AND A.MHP=? AND A.MEMAIL=?";
pstmt = conn.prepareStatement(sqls);
pstmt.clearParameters();
pstmt.setString(1, mvo.getMhp());
pstmt.setString(2, mvo.getMemail());
rsRs = pstmt.executeQuery();
if(rsRs != null) {
while (rsRs.next()) {
nCnt = rsRs.getInt(1);
// nCnt = rsRs.getInt("NCNT"); // 컬럼 명, 컬럼 명 앨리어스
}
}
if (nCnt ==1) bool = true;
// 임시 비밀번호를 보내기 위해 회원 정보에서 핸드폰과 이메일 확인
ArrayList<TpwVO> aList = null;
if (bool) {
// 임시 패스워드 불러오기
String tempPw = PasswordUtil.randomPW(8);
logger.info("tempPw >>> : " + tempPw);
// 패스워드 DB에 저장하기 : 암호화 할 것인가 고민해볼 것
EncryptAES ase = EncryptAES.getInstance();
String encryptTempPw = ase.aesEncode(tempPw);
logger.info("encryptTempPw >>> : " + encryptTempPw);
// 디비에 저장하기
Connection conn_1 = null;
PreparedStatement pstmt_1 = null;
int nCnt_1 = 0;
conn_1 = KosConnectivity.getConnection();
String sqls_1 = "INSERT INTO TEMP_TP (TNUM, THP, TEMAIL, TPW, INSERTDATE) VALUES (TEMP_PWSEQ.NEXTVAL, ?, ?, ?, SYSDATE)";
logger.info("INSEERT >>> : " + sqls_1);
pstmt_1 = conn_1.prepareStatement(sqls_1);
pstmt_1.clearParameters();
pstmt_1.setString(1, mvo.getMhp());
pstmt_1.setString(2, mvo.getMemail());
pstmt_1.setString(3, encryptTempPw);
nCnt = pstmt_1.executeUpdate();
if (nCnt == 0) {
Connection conn_s = null;
PreparedStatement pstmt_s = null;
ResultSet rsRs_s = null;
conn_s = KosConnectivity.getConnection();
String sqls_s = "SELECT * FROM TEMP_PW WHERE THP = ? AND TEMAIL = ?";
logger.info("SELECT >>> : " + sqls_s);
pstmt_s = conn_s.prepareStatement(sqls_s);
pstmt_s.clearParameters();
pstmt_s.setString(1, mvo.getMhp());
pstmt_s.setString(2, mvo.getMemail());
rsRs_s = pstmt_s.executeQuery();
if (rsRs_s != null) {
aList = new ArrayList<TpwVO>();
while (rsRs_s.next()) {
TpwVO tvo = new TpwVO();
tvo.setThp(rsRs_s.getString(1));
tvo.setTemail(rsRs_s.getString(2));
tvo.setTpw(rsRs_s.getString(3));
aList.add(tvo);
}
}
}
//디비에 저장된 암호화된 임시 비밀번호를 복호화 해서 메일 보내기
String decryptTempPw = ase.aesDecode(encryptTempPw);
logger.info("descryptTempPw >>> : " + decryptTempPw);
if (nCnt == 1) {
// 메일 보내기
String mailsubject = "임시 비밀번호 보내기";
String sendmail = "보내는사람 메일주소";
String mailpw = "보내는 사람 메일 주소 비밀번호";
String receivemail = "받는 사람 메일 주소";
String sendmsg = "임시 비밀번호 및 메시지 " + tempPw;
GmailVO gvo = null;
gvo = new GmailVO();
gvo.setMailsubject(mailsubject);
gvo.setSendmail(sendmail);
gvo.setMailpw(mailpw);
gvo.setReceivemail(receivemail);
gvo.setSendmsg(sendmsg);
GmailSend gms = new GmailSend();
gms.gmailSend(gvo);
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>pwTempSend</h3>
<hr>
</body>
</html>
- pwFind.jsp
<%@ 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>
<h3>패스워드 찾기</h3>
<hr>
<form action="/KosMember/kos_mail/pwTempSend.jsp"
method="POST"
enctype="application/x-www-urlencoded">
전화번호 <input type="text" class="mhp" name="mhp" id="mhp"><br>
이메일 <input type="text" class="memail" name="memail" id="memail"><br>
<input type="submit" id="pwBtn" value="보내기">
</form>
</body>
</html>
- login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>login</h3>
<hr>
<a href="/KosMember/kos_mail/pwFind.jsp">패스워드 찾기</a>
</body>
</html>
7교시 (16:30-17:20)
- EncryptSHA.java
package a.b.c.common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class EncryptSHA {
/*
암호화할 때 복호화가 불가능한 단반향 방식 암호화
SHA-2 Secure Hash Algorithm 2
해시 함수가 출력하는 압축닿 문장 다이제스트 Digest라고 한다.
SHA-2가 생성하는 다이제스트는 224, 256, 384, 512bit 등 다양
256bit : SHA-2를 SHA-256이라고 한다.
*/
public static String encryptSHA256(String s) {
String ss = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
System.out.println("md >>> : " + md);
md.update(s.getBytes());
byte byteData[] = md.digest();
System.out.println("byteData >>> : " + byteData);
StringBuffer sb = new StringBuffer();
for (int i=0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i]&0xff) + 0x100, 16).substring(1));
int tmp = byteData[i] & 0xff;
// System.out.println("tmp >>> : " + tmp);
int tmp_1 = 0x100;
// System.out.println("tmp_1 >>> : " + tmp_1);
int tmp_sum = tmp + tmp_1;
// System.out.println("tmp_sum >>> : " + tmp_sum);
String tmp_s = Integer.toString(tmp_sum, 16);
// System.out.println("tmp_s >>> : " + tmp_s_;
String tmp_s_1 = tmp_s.substring(1);
System.out.println("tmp_s_1 >>> : " + tmp_s_1);
}
ss = sb.toString();
} catch (NoSuchAlgorithmException e) {
System.out.println(e.getMessage());
}
return ss;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s= EncryptSHA.encryptSHA256("hg74111#");
System.out.println("s >>> : " + s);
}
}
- EncryptAES.java
package a.b.c.common;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
//import javax.crypto.BadPaddingException;
//import javax.crypto.IllegalBlockSizeException;
//import javax.crypto.NoSuchPaddingException;
//import java.security.InvalidKeyException;
//import java.security.NoSuchAlgorithmException;
//import java.security.InvalidAlgorithmParameterException;
import org.apache.commons.codec.binary.Base64;
public class EncryptAES {
final static String secretKey = "shplab123456789abcdefghijklmnopq"; // 32bit
static String IV = secretKey.substring(0, 16); // 16bit
// 싱글톤 패턴 적용 : 객체를 하나만 사용하세요 : 객체는 항상 메모리에 하나만 있어야 한다.
private EncryptAES() {
}
public static EncryptAES getInstance() {
return SingletonLazyHolder.INSTANCE;
}
private static class SingletonLazyHolder {
private static final EncryptAES INSTANCE = new EncryptAES();
}
// 암호화
public String aesEncode(String str) {
String enStr = "";
try {
byte[] keyData = secretKey.getBytes();
SecretKey secureKey = new SecretKeySpec(keyData, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes()));
byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
enStr = new String(Base64.encodeBase64(encrypted));
} catch (Exception e) {
}
return enStr;
}
// 복호화
public String aesDecode(String str) {
String deStr = "";
try {
byte[] keyData = secretKey.getBytes();
SecretKey secureKey = new SecretKeySpec(keyData, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, secureKey, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] byteStr = Base64.decodeBase64(str.getBytes());
deStr = new String(c.doFinal(byteStr), "UTF-8");
} catch (Exception e) {
}
return deStr;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String id = "shplab123";
EncryptAES ase = EncryptAES.getInstance();
String enId = ase.aesEncode(id);
String desId = ase.aesDecode(enId);
System.out.println("enId >>> : " + enId);
System.out.println("desId >>> : " + desId);
}
}
8교시 (17:30-18:30)
- TpwVO.java
package a.b.c.test.mail;
public class TpwVO {
private String tnum;
private String thp;
private String temail;
private String tpw;
private String insertdate;
// 생성자
public TpwVO() {
}
public TpwVO(String tnum, String thp, String temail, String tpw, String insertdate) {
super();
this.tnum = tnum;
this.thp = thp;
this.temail = temail;
this.tpw = tpw;
this.insertdate = insertdate;
}
// getter
public String getTnum() {
return tnum;
}
public String getThp() {
return thp;
}
public String getTemail() {
return temail;
}
public String getTpw() {
return tpw;
}
public String getInsertdate() {
return insertdate;
}
// setter
public void setTnum(String tnum) {
this.tnum = tnum;
}
public void setThp(String thp) {
this.thp = thp;
}
public void setTemail(String temail) {
this.temail = temail;
}
public void setTpw(String tpw) {
this.tpw = tpw;
}
public void setInsertdate(String insertdate) {
this.insertdate = insertdate;
}
}
- PasswordUtil.java
package a.b.c.common;
import java.util.UUID;
public abstract class PasswordUtil {
/*
자바 중복되지 않는 고유 키
UUID (Universally unique identifier)
슛자와 영어(소문자)만을 조합하여 임시 비밀번호 생성
32개 문자 + '-' = 36개
*/
public static String tempPW(int len) {
String u = UUID.randomUUID().toString();
// System.out.println("u >>> : " + u);
u = u.replace("-", "").substring(0, len);
System.out.println("u >>> : " + u);
return u;
}
public static String randomPW(int len) {
char c[] = {
'1','2','3','4','5','6','7','8','9','0',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'!','@','#','&'
//'!','@','#','$','%','^','&','*','(',')'
};
String p = "";
for (int i=0; i < len; i++) {
int a = (int)(Math.random()*(c.length));
p += c[a];
}
return p;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1 = PasswordUtil.tempPW(10);
String s2 = PasswordUtil.randomPW(10);
System.out.println("UUID >>> : " + s1);
System.out.println("random >>> : " + s2);
}
}
- pwTempSend.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- log4 객체 import -->
<%@ page import="org.apache.log4j.LogManager" %>
<%@ page import="org.apache.log4j.Logger" %>
<!-- PasswordUtil 객체 import -->
<%@ page import="a.b.c.common.PasswordUtil" %>
<%@ page import="a.b.c.common.EncryptAES" %>
<%@ page import="a.b.c.common.EncryptSHA" %>
<!-- mail 객체 import -->
<%@ page import="a.b.c.test.mail.GmailSend" %>
<%@ page import="a.b.c.test.mail.GmailVO" %>
<!-- 커넥션 클래스 import -->
<%@ page import="a.b.c.common.KosConnectivity" %>
<!-- java.sql.* JDBC 클래스 import -->
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<!-- 깡통 클래스 import -->
<%@ page import="a.b.c.kos.mem.vo.MemVO" %>
<%@ page import="a.b.c.test.mail.TpwVO" %>
<%@ page import="java.util.ArrayList" %>
<% request.setCharacterEncoding("UTF-8"); %>
<%
Logger logger = LogManager.getLogger(this.getClass());
logger.info("pwTempSend.jsp 페이지 >>> : ");
String mhp = request.getParameter("mhp");
String memail = request.getParameter("memail");
MemVO mvo = null;
mvo = new MemVO();
mvo.setMhp(mhp);
mvo.setMemail(memail);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rsRs = null;
int nCnt = 0;
boolean bool = false;
conn = KosConnectivity.getConnection();
String sqls = "SELECT COUNT(A.MNUM) NCNT FROM KOS_MEMBER A WHERE A.DELETEYN='Y' AND A.MHP=? AND A.MEMAIL=?";
pstmt = conn.prepareStatement(sqls);
pstmt.clearParameters();
pstmt.setString(1, mvo.getMhp());
pstmt.setString(2, mvo.getMemail());
rsRs = pstmt.executeQuery();
if(rsRs != null) {
while (rsRs.next()) {
nCnt = rsRs.getInt(1);
// nCnt = rsRs.getInt("NCNT"); // 컬럼 명, 컬럼 명 앨리어스
}
}
if (nCnt ==1) bool = true;
// 임시 비밀번호를 보내기 위해 회원 정보에서 핸드폰과 이메일 확인
ArrayList<TpwVO> aList = null;
if (bool) {
// 임시 패스워드 불러오기
String tempPw = PasswordUtil.randomPW(8);
logger.info("tempPw >>> : " + tempPw);
// 패스워드 DB에 저장하기 : 암호화 할 것인가 고민해볼 것
EncryptAES ase = EncryptAES.getInstance();
String encryptTempPw = ase.aesEncode(tempPw);
logger.info("encryptTempPw >>> : " + encryptTempPw);
// 디비에 저장하기
Connection conn_1 = null;
PreparedStatement pstmt_1 = null;
int nCnt_1 = 0;
conn_1 = KosConnectivity.getConnection();
String sqls_1 = "INSERT INTO TEMP_TP (TNUM, THP, TEMAIL, TPW, INSERTDATE) VALUES (TEMP_PWSEQ.NEXTVAL, ?, ?, ?, SYSDATE)";
logger.info("INSEERT >>> : " + sqls_1);
pstmt_1 = conn_1.prepareStatement(sqls_1);
pstmt_1.clearParameters();
pstmt_1.setString(1, mvo.getMhp());
pstmt_1.setString(2, mvo.getMemail());
pstmt_1.setString(3, encryptTempPw);
nCnt = pstmt_1.executeUpdate();
if (nCnt == 0) {
Connection conn_s = null;
PreparedStatement pstmt_s = null;
ResultSet rsRs_s = null;
conn_s = KosConnectivity.getConnection();
String sqls_s = "SELECT * FROM TEMP_PW WHERE THP = ? AND TEMAIL = ?";
logger.info("SELECT >>> : " + sqls_s);
pstmt_s = conn_s.prepareStatement(sqls_s);
pstmt_s.clearParameters();
pstmt_s.setString(1, mvo.getMhp());
pstmt_s.setString(2, mvo.getMemail());
rsRs_s = pstmt_s.executeQuery();
if (rsRs_s != null) {
aList = new ArrayList<TpwVO>();
while (rsRs_s.next()) {
TpwVO tvo = new TpwVO();
tvo.setThp(rsRs_s.getString(1));
tvo.setTemail(rsRs_s.getString(2));
tvo.setTpw(rsRs_s.getString(3));
aList.add(tvo);
}
}
}
//디비에 저장된 암호화된 임시 비밀번호를 복호화 해서 메일 보내기
String decryptTempPw = ase.aesDecode(encryptTempPw);
logger.info("descryptTempPw >>> : " + decryptTempPw);
if (nCnt == 1) {
// 메일 보내기
String mailsubject = "임시 비밀번호 보내기";
String sendmail = "보내는사람 메일주소";
String mailpw = "보내는 사람 메일 주소 비밀번호";
String receivemail = "받는 사람 메일 주소";
String sendmsg = "임시 비밀번호 및 메시지 " + tempPw;
GmailVO gvo = null;
gvo = new GmailVO();
gvo.setMailsubject(mailsubject);
gvo.setSendmail(sendmail);
gvo.setMailpw(mailpw);
gvo.setReceivemail(receivemail);
gvo.setSendmsg(sendmsg);
GmailSend gms = new GmailSend();
gms.gmailSend(gvo);
}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>pwTempSend</h3>
<hr>
</body>
</html>
Notes
- 앞으로 진도
- 스크립트
- checkbox
- radio
- selectbox
- 파일 업로드
- 메일
- 지도 서비스
- 시각화: 차트
- Open API : 날씨, 공공정보
- SNS 로그인
- 아이디, 패스워드 찾기
- 스크립트
728x90