[프로젝트 생성]
언어셋 설정
서버 설정
빌드패스 설정
디비 설정 => ⭐️디비 버전에 맞는 라이브러리 점프
자바 EE툴 => xml파일 생성
jQuery 사용시 js파일로 넣기
[xml파일 주의사항]
프로젝트명와 패키지명이 같으면 url-pattern에 패키지명을 안써도됨
ECMA-Script
React or Vue
점점 Vue로 바뀌는 추세
[PC-WEB]
React or Vue : CDN 형태로 제작
ECMA-Script
jQuery
[Mobile-WEB + 하이브리드 앱]
React or Vue : CLI 형태로 제작
ECMA-Script
[jQuery 다운]
Download the uncompressed development version of jQuery 3.7.1
=> 엔진 커스텀해서 사용할때 (경량화, 실력자, 이거쓸수있으면 연봉이바뀜 !)
Download jQuery 3.7.1 slim build
=> 엔진을 커스텀하지 않고 사용할때
+--------------------+
| 메일 작성 (mail.jsp) |
+--------------------+
↓
+------------------------+
| 입력 검증 (JavaScript) |
+------------------------+
↓
+----------------------+
| 서버 전송 (mailok.java) |
+----------------------+
↓
+-----------------------------+
| 데이터 저장 (mail_insert.java) |
+-----------------------------+
↓
+-----------------------------+
| 메일 목록 조회 (mail_list.java) |
+-----------------------------+
↓
+----------------------------+
| 메일 목록 표시 (mail_list.jsp) |
+----------------------------+
↓
+-------------------------+
| 메일 삭제 (mail_del.java) |
+-------------------------+
mail.jsp
메일쓰기 페이지
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>메일 전송 시스템</title>
<script src="./js/jquery.js"></script>
<script>
$(function() {
//. : class 호출
//# : id 호출
//$("#btn").on("click",function() //옛날버전! 1~2점대 버전
$("#btn").click(function() { //요즘버전 3점대
if ($("#to_name").val() == "") {
alert("담당자성함을 입력하세요");
} else if ($("#to_mail").val() == "") {
alert("회신받을 메일주소를 입력하세요");
} else if ($("#subject").val() == "") {
alert("제목을 입력하세요");
} else if ($("#context").val() == "") {
alert("내용을 입력하세요");
} else{
//test() : 단어를 검토하여 true 또는 false를 출력하며 정규식 코드를 확인함
//var $word = "123a123";
//var $reg = /[0-9]/g; //0~9가 하나라도 있으면 true
//var $reg = /[^0-9]/g; //0~9가 아닌게 하나라도 있으면 true
//var $reg = /^[0-9]/g; //0~9로 시작하면 true
//var $reg = /[a-zA-Z]/g; //아래와 같은 코드
//var $reg = /[a-z]/gi; //옵션 i : 대소문자 모두 체크
//console.log($reg.test($word));
// 정규식 코드의 \ : 특정 문자를 기준으로 함
var $reg = /^[a-z0-9]([a-z0-9-_.])+\@[a-z0-9ㄱ-힇_-]+\.[a-z0-9ㄱ-힇]{2,}/i; //정규식코드에는 절대 띄워쓰기 X
//a-z0-9로 시작하고 그다음에 ()이면 true
if($reg.test($("#to_mail").val())==false){
alert("올바른 이메일 주소를 입력하세요");
$("#to_mail").val(""); //jQuery로 사용자가 입력한 값을 초기화
}else{
//frm.submit(); //js 버전
$("#frm").submit(); //jQuery 버전 : id값으로 form태그를 실행
}
}
});
});
</script>
<style>
.area{
width:300px;
height:300px;
resize:none;
}
</style>
</head>
<body>
<form id="frm" method="post" action="./mailok.do">
담당자 성함 : <input type="text" id="to_name" name="to_name"><br>
회신받을 메일주소 : <input type="text" id="to_mail" name="to_mail"><br>
제목 : <input type="text" id="subject" name="subject"><br>
제휴 내용 : <textarea class="area" id="context" name="context"></textarea><br>
<input type="button" id="btn" value="제휴 문의">
</form>
</body>
</html>
mailok.java (servlet)
View에서 가져온 메일 데이터를 Model을 이용해 DB에 삽입하는 Controller
package portfolio;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class mailok extends HttpServlet {
private static final long serialVersionUID = 1L;
mail_insert mi = new mail_insert();
PrintWriter pw = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //Front-end에서 한글이 전송될 경우
response.setContentType("text/html;charset=utf-8"); //javascript 사용할 경우
String to_name = request.getParameter("to_name");
String to_mail = request.getParameter("to_mail");
String subject = request.getParameter("subject");
String context = request.getParameter("context");
int result = this.mi.mail_in(to_name,to_mail,subject,context);
this.pw = response.getWriter();
if(result > 0) {
this.pw.write("<script>"
+ "alert('정상적으로 제휴 문의가 등록되었습니다.');"
+ "location.href='./mail_list.do';"
+ "</script>");
}else {
this.pw.write("<script>"
+ "alert('서비스 장애로 인하여 문의실패!');"
+ "history.go(-1);"
+ "</script>");
}
}
}
mail_insert.java (class)
위 서블릿파일에서 사용
메일 데이터를 db에 저장하는 Model
package portfolio;
import java.sql.Connection;
import java.sql.PreparedStatement;
// 메일로 접수된 사항을 db로 저장하는 Model
public class mail_insert {
Connection con = null;
PreparedStatement ps = null;
String sql;
int result;
m_dbinfo db = new m_dbinfo();
public int mail_in(String to_name, String to_mail, String subject, String context) {
try {
System.out.println("mailin");
this.con = this.db.dbinfo();
System.out.println("mailin2");
this.sql = "insert into koo_mail (midx, to_name, to_mail, subject, context, maildate) "
+ "values ('0',?,?,?,?,now())";
this.ps = this.con.prepareStatement(this.sql);
this.ps.setString(1,to_name);
this.ps.setString(2,to_mail);
this.ps.setString(3,subject);
this.ps.setString(4,context);
this.result = this.ps.executeUpdate();
}catch (Exception e) {
System.out.println(e);
this.result = 0;
}finally {
try {
this.ps.close();
this.con.close();
}catch (Exception e) {
System.out.println(e);
System.out.println("데이터베이스 비정상 접속해제");
}
}
return this.result;
}
}
m_dbinfo.java (class)
위 파일에서 사용
db 환경설정 Model
package portfolio;
//Database를 사용하기 위해서는 해당 프로젝트에 DB버전에 맞는 라이브러리를 먼저 load해야 함
import java.sql.Connection;
import java.sql.DriverManager;
public class m_dbinfo {
public static Connection dbinfo() {
String db = "com.mysql.jdbc.Driver"; //Database 사용 라이브러리 명(드라이버)
String db_url = "jdbc:mysql://kbsn.or.kr:3306/bluedb"; // Database접속 경로
String db_user = "memebera"; //Database접속 ID
String db_pass = "a123456"; //Database접속 password
Connection con = null;
try {
Class.forName(db); //라이브러리 사용
con = DriverManager.getConnection(db_url, db_user, db_pass);
System.out.println(con);
} catch (Exception e) {
System.out.println("Database 연결 실패!!");
}
return con;
}
}
mail_list.java (servlet)
Model을 이용해 DB의 데이터를 가져와 전달하는 Controller
package portfolio;
import java.io.IOException;
import java.util.ArrayList;
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 mail_list extends HttpServlet {
private static final long serialVersionUID = 1L;
mail_select ms = new mail_select();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<ArrayList<String>> alldata = this.ms.maillist(); //Model 결과값 받음
request.setAttribute("alldata", alldata); //jsp에 데이터 전달
RequestDispatcher rd = request.getRequestDispatcher("./mail_list.jsp");
rd.forward(request, response);
}
}
mail_select.java (class)
위 서블릿파일에서 사용
db에서 데이터를 가져오는 Model
package portfolio;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
public class mail_select {
Connection con = null;
PreparedStatement ps = null;
m_dbinfo db = new m_dbinfo();
String sql;
int result;
ResultSet rs = null; //select문에 사용하는 결과 저장뭐시기
ArrayList<String> data = null; //내 정보 가져올땐 1차
ArrayList<ArrayList<String>> alldata = null; //여러명 정보 가져올땐 2차
public ArrayList<ArrayList<String>> maillist(){
try {
this.con = this.db.dbinfo();
//select안의 select를 안쓴 쿼리문 //이거쓰면 코드가 길어짐;;;;
//this.sql = "select midx,to_name,to_mail,subject,maildate from koo_mail order by midx desc limit 0,2";
//페이지를 쪼갤때 limit 사용시 주의사항 : 전체 게시물 수도 잘려버림 => select안의 select 사용하기
this.sql = "select midx,to_name,to_mail,subject,maildate,"
+ "(select count(*) from koo_mail) as total "
+ "from koo_mail order by midx desc limit 0,2;";
this.ps = this.con.prepareStatement(this.sql);
this.rs = this.ps.executeQuery();
this.alldata = new ArrayList<ArrayList<String>>();
//select안의 select를 모르면 생기는 코드
/*
String sql2 = "select count(*) as total from koo_mail";
this.ps = this.con.prepareStatement(sql2);
ResultSet rs2 = this.ps.executeQuery();
rs2.next();
*/
while(this.rs.next()) {
this.data = new ArrayList<String>();
this.data.add(this.rs.getString("midx"));
this.data.add(this.rs.getString("to_name"));
this.data.add(this.rs.getString("to_mail"));
this.data.add(this.rs.getString("subject"));
this.data.add(this.rs.getString("maildate"));
/*
this.data.add(rs2.getString("total"));
*/
//select 안의 select 쓴 경우
this.data.add(this.rs.getString("total"));
this.alldata.add(this.data);
}
/*
rs2.close();
*/
}catch (Exception e) {
this.alldata = null;
}finally {
try {
/*
this.ps.close();
this.rs.close();
*/
this.con.close();
}catch (Exception e) {
System.out.println("Database 오류 발생");
}
}
return this.alldata;
}
}
mail_list.jsp
메일 목록 페이지
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//ArrayList<ArrayList<String>> alldata = (ArrayList<ArrayList<String>>)request.getAttribute("alldata");
ArrayList<ArrayList<String>> alldata = (ArrayList)request.getAttribute("alldata"); //윗줄과 동일
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>메일 </title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0">
<thead>
<tr height="30">
<th width="100">번호</th>
<th width="450" >제목</th>
<th width="200">의뢰인 메일주소</th>
<th width="150">의뢰일자</th>
</tr>
</thead>
<tbody>
<p>[총 제휴의뢰 건수] : <%=alldata.get(0).get(5) %></p>
<%
int w = 0;
int no = Integer.parseInt(alldata.get(0).get(5));
while(w < alldata.size()){
//제목 길이 제한 15자 이상이 되었을 경우 말줄임표를 사용
String sj = "";
if(alldata.get(w).get(3).length() > 15){
sj = alldata.get(w).get(3).substring(0,15) + "...";
}else{
sj = alldata.get(w).get(3);
}
%>
<tr height="30" align="center">
<td><%=no %></td>
<!--
마우스 가져갔을때 전체 이름 보이는거 title속성 사용
마우스 올리면 시각장애인한테 읽어줌 조음
-->
<td align="left" title="<%= alldata.get(w).get(3)%>"><%=sj%>
<input type=button" value="삭제" onclick="mail_delete(<%= alldata.get(w).get(0)%>)"></td>
<td><%=alldata.get(w).get(1)%>(<%=alldata.get(w).get(2)%>)</td>
<td><%=alldata.get(w).get(4).substring(0,10)%></td>
</tr>
<%
no--;
w++;
}
%>
</tbody>
<script>
function mail_delete(n){
if(confirm("해당 게시물을 삭제시 데이터 복구되지 않습니다.")){
location.href='./mail_del.do?mix='+n;
}
}
</script>
</table>
</body>
</html>
- 한 페이지의 게시물 수 제한 => DB 쿼리문 limit 사용 => 총개수도 영향을 받음
=> select 안의 select문 사용해서 총개수를 따로 받기 //select 안의 select문을 사용하지 않으면 코드가 매우 길어짐! - 제목 길이 제한 => substring으로 자르기
=> 마우스를 올렸을때 제목이 다보이게 input태그에 title속성 넣기
mail_del.java (servlet)
DB의 데이터를 삭제하는 Controller
package portfolio;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class mail_del extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection con = null;
PreparedStatement ps = null;
String sql = null;
int result = 0;
m_dbinfo db = new m_dbinfo();
PrintWriter pw = null;
//삭제는 간단해서 모델을 잘 안만듦
//대신 복구가 불가능하기 때문에 신경쓰기
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
this.pw = response.getWriter();
try {
String midx = request.getParameter("midx"); //프론트엔드 get 전송
this.con = this.db.dbinfo();
this.sql = "delete from koo_mail where midx=?";
this.ps = this.con.prepareStatement(this.sql);
this.ps.setString(1, midx);
this.result = this.ps.executeUpdate(); //i,d,u 는 executeUpdate() 사용
if(result > 0) {
//this.pw.write(""); 아래 코드와 동일
this.pw.print("<script>"
+ "alert('해당 게시물을 정상적으로 삭제했습니다.');"
+ "location.href='./mail_list.do';"
+ "</script");
}
}catch (Exception e) {
this.pw.print("<script>"
+ "alert('데이터 삭제 부분에 문제가 발생하였습니다.');"
+ "location.href='./mail_list.do';"
+ "</script");
}finally {
try {
this.ps.close();
this.con.close();
this.pw.close();
}catch (Exception e) {
System.out.println(e);
}
}
}
}