목차 | |
1. | Login |
1. Login
▣ sqlFile.sql
create table board(
bno int auto_increment,
title varchar(500) not null,
writer varchar(100) not null,
content text,
regdate datetime default now(),
moddate datetime default now(),
primary key(bno));
-- 2024.10.23
-- 댓글(comment)
create table comment(
cno int auto_increment,
bno int not null,
content varchar(2000) not null,
writer varchar(500) default "unknown",
regdate datetime default now(),
primary key(cno));
-- 10.24
-- 조회수
alter table board add column readCount int default 0;
-- 파일
alter table board add imageFile varchar(500);
-- 10.25
create table member(
id varchar(100) not null,
pwd varchar(100) not null,
email vatchar(200) not null,
phone varchar(50),
regdate datetime default now(),
lastlogin datetime default now(),
primary key(id));
▣ MemberVO.java
package domain;
public class MemberVO {
private String id;
private String pwd;
private String email;
private String phone;
private String regdate;
private String lastlogin;
public MemberVO() {}
//관리자 입장 / 사용자 입장
//회원등급 : admin(사이트관리자), manager(각 파트의 최고관리자), user(사용자)
//회원가입(수정) : id, pwd, email, phone
public MemberVO(String id, String pwd, String email, String phone) {
this.id = id;
this.pwd = pwd;
this.email = email;
this.phone = phone;
}
//로그인 : id, pwd
public MemberVO(String id, String pwd) {
this.id = id;
this.pwd = pwd;
}
//회원정보수정 : 관리자만 접근가능 전체
public MemberVO(String id, String pwd, String email, String phone, String regdate, String lastlogin) {
this.id = id;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.regdate = regdate;
this.lastlogin = lastlogin;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRegdate() {
return regdate;
}
public void setRegdate(String regdate) {
this.regdate = regdate;
}
public String getLastlogin() {
return lastlogin;
}
public void setLastlogin(String lastlogin) {
this.lastlogin = lastlogin;
}
@Override
public String toString() {
return "MemberVO [id=" + id + ", pwd=" + pwd + ", email=" + email + ", phone=" + phone + ", regdate=" + regdate
+ ", lastlogin=" + lastlogin + "]";
}
}
▣ MemberController.java
package controller;
import java.io.IOException;
import java.util.List;
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 javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import domain.MemberVO;
import service.MemberService;
import service.MemberServiceImpl;
@WebServlet("/mem/*")
public class MemberController extends HttpServlet {
private static final long serialVersionUID = 1L;
//로그객체
private static final Logger log = LoggerFactory.getLogger(MemberController.class);
//동기방식 : requestDispatcher : request에 대한 응답 데이터를 jsp(html) 화면으로 전송하는 역할
private RequestDispatcher rdp;
//목적지 주소
private String destPage;
private int isOk;
//service
private MemberService msv;
public MemberController() {
msv = new MemberServiceImpl();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 처리
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=UTF-8");
// 요청주소 추출
String uri = request.getRequestURI();
String path = uri.substring(uri.lastIndexOf("/")+1);
log.info(">>>> member path > {}", path);
switch(path) {
case "join":
destPage="/member/join.jsp";
break;
case "register":
try {
//jsp에서 온 파라미터 받기
//member 객체 생성 후 service 에게 등록 요청
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
MemberVO mvo = new MemberVO(id, pwd, email, phone);
isOk = msv.join(mvo);
log.info(" >>>> join > {} ", (isOk>0? "OK":"FAIL"));
destPage = "/index.jsp";
} catch (Exception e) {
log.info("join error!!");
e.printStackTrace();
}
break;
case "login":
try {
// 로그인 : id, pwd 파라미터로 받아서 DB에 해당 id가 있는지 확인, pwd가 일치하는지 확인
// 정보를 가져와서 session 객체에 저장
// session : 모든 jsp에 공유되는 객체 / 브라우저가 종료되면 삭제
// ${변수명}
String id = request.getParameter("id");
String pwd = request.getParameter("pwd");
MemberVO mvo = new MemberVO(id, pwd);
MemberVO loginMvo = msv.login(mvo);
// 로그인 정보가 잘못되면 loginMvo는 null 로 출력
log.info(">>>> loginMvo > {}", loginMvo);
// session 에 저장
if(loginMvo != null) {
// 로그인이 성공했다면...
// 세션에 저장
HttpSession ses = request.getSession();
ses.setAttribute("ses", loginMvo);
//로그인 유지시간 초단위로 설정 10분
ses.setMaxInactiveInterval(10*60);
}else {
//로그인이 실패했다면... index.jsp로 메시지 전송
request.setAttribute("msg_login", -1);
}
destPage = "/index.jsp";
} catch (Exception e) {
log.info("login error");
e.printStackTrace();
}
break;
case "logout":
try {
//session에 값이 있다면 해당 세션을 끊어라.
HttpSession ses = request.getSession();
MemberVO mvo = (MemberVO)ses.getAttribute("ses");
log.info(">>>> ses 에서 추출한 mvo > {}", mvo);
// lastlogin update
isOk = msv.lastLogin(mvo.getId());
log.info(">>>> lastLogin update >> {}", (isOk>0? "OK":"FAIL"));
ses.invalidate(); //세션 무효화(세션 끊기)
destPage="/index.jsp";
} catch (Exception e) {
log.info("logout error");
e.printStackTrace();
}
break;
case "list":
try {
List<MemberVO> list = msv.getList();
log.info(">>>> list mvo > {}", list);
request.setAttribute("list", list);
destPage = "/member/list.jsp";
} catch (Exception e) {
e.printStackTrace();
}
break;
case "modify":
try {
destPage = "/member/modify.jsp";
} catch (Exception e) {
e.printStackTrace();
}
break;
case "update":
try {
String pwd = request.getParameter("pwd");
HttpSession ses = request.getSession();
if(pwd.length() <= 0 || pwd==null) {
pwd = ((MemberVO)ses.getAttribute("ses")).getPwd();
}
MemberVO mvo = new MemberVO(
request.getParameter("id"),
pwd,
request.getParameter("email"),
request.getParameter("phone")
);
isOk = msv.modify(mvo);
log.info(">>>> modify mvo > {}", isOk>0?"OK":"FAIL");
if(isOk == 0) {
request.setAttribute("msg_update", "fail");
}else {
ses.setAttribute("ses", mvo);
}
destPage="/index.jsp";
} catch (Exception e) {
e.printStackTrace();
}
break;
case "delete":
HttpSession ses = request.getSession();
String id = ((MemberVO)ses.getAttribute("ses")).getId();
isOk = msv.delete(id);
log.info(">>>> delete mvo > {}", isOk>0?"OK":"FAIL");
if(isOk > 0) {
request.setAttribute("msg_delete", "ok");
}
ses.invalidate();
destPage = "/index.jsp";
break;
}
// rdp 전송
rdp = request.getRequestDispatcher(destPage);
rdp.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
service(request, response);
}
}
▣ MemberService.java
package service;
import java.util.List;
import domain.MemberVO;
public interface MemberService {
int join(MemberVO mvo);
MemberVO login(MemberVO mvo);
int lastLogin(String id);
List<MemberVO> getList();
int modify(MemberVO mvo);
int delete(String id);
}
▣ MemberServiceImpl.java
package service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import dao.MemberDAO;
import dao.MemberDAOImpl;
import domain.MemberVO;
public class MemberServiceImpl implements MemberService {
private static final Logger log = LoggerFactory.getLogger(MemberServiceImpl.class);
private MemberDAO mdao;
public MemberServiceImpl() {
mdao = new MemberDAOImpl();
}
@Override
public int join(MemberVO mvo) {
// TODO Auto-generated method stub
return mdao.join(mvo);
}
@Override
public MemberVO login(MemberVO mvo) {
// TODO Auto-generated method stub
return mdao.login(mvo);
}
@Override
public int lastLogin(String id) {
// TODO Auto-generated method stub
return mdao.lastLogin(id);
}
@Override
public List<MemberVO> getList() {
// TODO Auto-generated method stub
return mdao.getList();
}
@Override
public int modify(MemberVO mvo) {
// TODO Auto-generated method stub
return mdao.update(mvo);
}
@Override
public int delete(String id) {
// TODO Auto-generated method stub
return mdao.delete(id);
}
}
▣ MemberDAO.java
package dao;
import java.util.List;
import domain.MemberVO;
public interface MemberDAO {
int join(MemberVO mvo);
MemberVO login(MemberVO mvo);
int lastLogin(String id);
List<MemberVO> getList();
int update(MemberVO mvo);
int delete(String id);
}
▣ MemberDAOImpl.java
package dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import domain.MemberVO;
import orm.DatabaseBuilder;
public class MemberDAOImpl implements MemberDAO {
private static final Logger log = LoggerFactory.getLogger(MemberDAOImpl.class);
private SqlSession sql;
public MemberDAOImpl() {
new DatabaseBuilder();
sql = DatabaseBuilder.getFactory().openSession();
}
@Override
public int join(MemberVO mvo) {
log.info("join dao in!!");
int isOk = sql.insert("MemberMapper.join", mvo);
if(isOk > 0) sql.commit();
return isOk;
}
@Override
public MemberVO login(MemberVO mvo) {
log.info("login dao in!!");
return sql.selectOne("MemberMapper.login", mvo);
}
@Override
public int lastLogin(String id) {
log.info("lastLogin up dao in!!");
int isOk = sql.update("MemberMapper.last", id);
if(isOk>0) sql.commit();
return isOk;
}
@Override
public List<MemberVO> getList() {
// TODO Auto-generated method stub
return sql.selectList("MemberMapper.list");
}
@Override
public int update(MemberVO mvo) {
log.info("update dao in!!");
int isOk = sql.update("MemberMapper.up", mvo);
if(isOk>0) sql.commit();
return isOk;
}
@Override
public int delete(String id) {
log.info("delete dao in!!");
int isOk = sql.update("MemberMapper.del", id);
if(isOk>0) sql.commit();
return isOk;
}
}
▣ memberMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="MemberMapper">
<insert id="join">
insert into member(id, pwd, email, phone)
values(#{id},#{pwd},#{email},#{phone})
</insert>
<select id="login" resultType="domain.MemberVO">
select * from member where id=#{id} and pwd=#{pwd}
</select>
<update id="last">
update member set lastlogin = now()
where id=#{id}
</update>
<select id="list" resultType="domain.MemberVO">
select * from member order by regdate desc
</select>
<update id="up">
update member set pwd=#{pwd}, email = #{email}, phone=#{phone}
where id = #{id}
</update>
<delete id="del">
delete from member where id=#{id}
</delete>
</mapper>
▣ mybatisConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/javadb"/>
<property name="username" value="javaUser"/>
<property name="password" value="mysql"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/boardMapper.xml"/>
<mapper resource="mapper/commentMapper.xml"/>
<mapper resource="mapper/memberMapper.xml"/>
</mappers>
</configuration>
▣ join.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>
<h1>회원가입 Page</h1>
<form action="/mem/register" method="post">
id:<br>
<input type="text" name="id" placeholder="id..."><br>
pwd:<br>
<input type="password" name="pwd" placeholder="pwd..."><br>
email:<br>
<input type="text" name="email" placeholder="email..."><br>
phone:<br>
<input type="text" name="phone" placeholder="phone..."><br>
<button type="submit">join</button>
</form>
</body>
</html>
▣ list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Member List Page</h1>
<table>
<thead>
<tr>
<th>id</th>
<th>email</th>
<th>phone</th>
<th>regDate</th>
<th>lastLogin</th>
</tr>
</thead>
<tbody>
<c:forEach items="${list }" var="mvo">
<tr>
<td>${mvo.id }</td>
<td><a href="/mem/modify">${mvo.email }</a></td>
<td>${mvo.phone }</td>
<td>${mvo.regdate }</td>
<td>${mvo.lastlogin }</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
▣ modify.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>
<h1>Member Modify Page</h1>
<hr>
<form action="/mem/update" method="post">
<table>
<tbody>
<tr>
<input type="hidden" name ="id" value="${ses.id }" />
<th>id</th>
<td>${ses.id }</td>
</tr>
<tr>
<th>pwd</th>
<td><input type="text" name ="pwd" placeholder="pwd..."></td>
</tr>
<tr>
<th>email</th>
<td><input type="text" name ="email" value="${ses.email }"></td>
</tr>
<tr>
<th>phone</th>
<td><input type="text" name ="phone" value="${ses.phone }"></td>
</tr>
<tr>
<th>regDate</th>
<td>${ses.regdate }</td>
</tr>
<tr>
<th>lastLogin</th>
<td>${ses.lastlogin }</td>
</tr>
</tbody>
</table>
<button type="submit">modify</button>
<a href="/mem/delete"><button type="button">delete</button></a>
<a href="/index.jsp"><button type="button">index</button></a>
</form>
</body>
</html>
▣ index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome to JSP World~!!</h1>
<hr>
<h5><a href="/mem/join">회원가입</a></h5>
<div>
<c:if test="${ses.id eq null }">
<form action="/mem/login" method="post">
id : <input type="text" name="id" placeholder="id...">
pwd: <input type="password" name="pwd" placeholder="pwd...">
<button type="submit">login</button>
</form>
</c:if>
</div>
<div>
<!-- 로그인 이후 나와야 하는 정보 : ses 객체가 있는지 없는지 확인 -->
<!-- eq : equals ne : not equals -->
<c:if test="${ses.id ne null }">
${ses.id }님이 login 하셨습니다.<br>
계정생성일 : ${ses.regdate } / 마지막접속일 : ${ses.lastlogin }<br>
<a href="/mem/modify"><button type="button">회원정보수정</button></a>
<c:if test="${ses.id eq 'admin' }">
<a href="/mem/list"><button type="button">회원리스트</button></a>
</c:if>
<a href="/brd/mylist"><button type="button">내가 쓴글 보기</button></a>
<a href="/mem/logout"><button type="button">logout</button></a>
</c:if>
</div>
<h3><a href="/brd/register">board 글쓰기 페이지로 이동</a></h3>
<!-- jsp의 모든 경로는 controller로 이동되게 해야함. -->
<h3><a href="/brd/list">board 리스트 페이지로 이동</a></h3>
<script type="text/javascript">
const msg_login = `<c:out value="${msg_login}" />`;
if(msg_login == '-1'){
alert("로그인 정보가 일치하지 않습니다.");
}
const msg_update = `<c:out value="${msg_update}" />`;
if(msg_update == 'fail'){
alert("회원정보가 수정되지 않습니다.");
}
const msg_delete = `<c:out value="${msg_delete}" />`;
if(msg_delete == 'ok'){
alert("회원 탈퇴가 완료되었습니다.");
}
</script>
</body>
</html>
▣ board_detail.js
/**
*
*/
console.log("board_detail.js in!!!");
console.log(bnoVal);
//등록 post
// 등록 버튼을 누르면 작성자와 댓글 내용의 값을 객체로 생성 => controller로 전송
document.getElementById('cmtAddBtn').addEventListener('click',()=>{
let cmtText = document.getElementById('cmtText').value;
let cmtWriter = document.getElementById('cmtWriter').value;
if(cmtText == null || cmtText==''){
alert("댓글을 입력해주세요.");
return false;
}
// 댓글 객체 생성
let cmtData = {
bno : bnoVal,
writer : cmtWriter,
content : cmtText
}
//댓글을 비동기로 전송
postCommentToServer(cmtData).then(result => {
console.log(result); // isOk
if(result == '1'){
alert("댓글등록성공!!");
}else{
alert("댓글등록실패!!");
}
//댓글 출력
printList(bnoVal);
});
});
function printList(bnoVal){
getCommentListFromServer(bnoVal).then(result => {
console.log(result);
if(result.length > 0){
printCommentList(result);
}else{
let div = document.getElementById('commentLine');
div.innerHTML=`<div> comment가 없습니다. </div>`;
}
});
}
function printCommentList(result){
let div = document.getElementById('commentLine');
div.innerText=''; //기존에 값이 있다면... 구조 지우기
for(let i=0; i<result.length; i++){
let html = `<div>`;
html += `<div>${result[i].cno}, ${result[i].bno}, ${result[i].writer}, ${result[i].regdate}</div>`;
html += `<div>`;
html += `<button type="button" data-cno="${result[i].cno}" class="cmtModBtn">수정</button>`;
html += `<button type="button" data-cno="${result[i].cno}" class="cmtDelBtn">삭제</button><br>`;
html += `<input type="text" class="cmtText" id="${result[i].cno}" value="${result[i].content}">`;
html += `</div></div><hr>`;
div.innerHTML += html; //각 댓글 객체를 누적하여 담기
}
}
//화면에서 데이터를 만들어서 보내는 방법 = post
//데이터를 보낼때 method=post, headers(Content-Type), body 를 작성해서 전송
//서버에서 데이터를 주는 방법 = get
//Content-Type : application/json; charset=utf-8
async function postCommentToServer(cmtData){
try{
console.log(cmtData);
const url = "/cmt/post";
const config={
method: 'post',
headers:{
'Content-Type':'application/json; charset=utf-8'
},
body: JSON.stringify(cmtData)
};
const resp = await fetch(url, config);
const result = await resp.text(); //isOk 값을 text로 리턴
return result;
}catch(error){
console.log(error);
}
}
//list 가져오기 : 내 게시글에 달린 댓글만 가져오기 => get (생략가능)
async function getCommentListFromServer(bno){
try{
const resp = await fetch("/cmt/list?bno="+bno);
const result = await resp.json(); // 댓글 리스트 [{...},{...},{...}]
return result;
}catch(error){
console.log(error);
}
};
async function updateCommentToServer(cmtData){
// 수정 : cno, content 객체를 보내서 isOk return => post
try{
const url = "/cmt/modify";
const config = {
method : 'post',
headers :{
'Content-Type':'application/json; charset=utf-8'
},
body: JSON.stringify(cmtData)
}
const resp = await fetch(url, config);
const result = await resp.text();
return result;
}catch(error){
console.log(error);
}
}
async function removeCommentToServer(cnoVal){
try{
const resp = await fetch("/cmt/remove?cno="+cnoVal);
const result = await resp.text();
return result;
}catch(error){
console.log(error);
}
}
document.addEventListener('click',(e)=>{
console.log(e.target);
console.log(e.target.dataset.cno);
//수정
if(e.target.classList.contains('cmtModBtn')){
//수정에 대한 처리
let cnoVal = e.target.dataset.cno;
//cno 값을 id로 사용할 경우
let cmtText = document.getElementById(cnoVal).value;
console.log(cmtText);
let cmtData = {
cno : cnoVal,
content : cmtText
}
updateCommentToServer(cmtData).then(result =>{
console.log(result);
if(result == '1'){
alert("댓글 수정 성공!!");
}else{
alert("댓글 수정 실패~!!");
}
// 수정 후 수정된 내용 출력
printList(bnoVal);
});
//내 타겟을 기준으로 가장 가까운 div를 찾기 closest('div')
//let div = e.target.closest('div');
//console.log(div); //내 댓글 객체 찾기
//let cmtText2 = div.querySelector('.cmtText').value;
//console.log(cmtText2);
}
//삭제
if(e.target.classList.contains('cmtDelBtn')){
//삭제에 대한 처리
let cnoVal = e.target.dataset.cno;
// 삭제 비동기 함수 호출 result 받아서 alert 띄우기.
removeCommentToServer(cnoVal).then(result =>{
// 삭제 후 출력 메서드 호출
if(result =='1'){
alert("삭제성공!!");
}else{
alert("삭제실패!!");
}
printList(bnoVal);
})
}
})
▷ 출력
'Java > JSP' 카테고리의 다른 글
JSP 기초(File) - AWS 풀스택 과정 63일차 (0) | 2024.10.24 |
---|---|
JSP 기초(DB Join) - AWS 풀스택 과정 62일차 (0) | 2024.10.23 |
JSP 기초(DB 연결) - AWS 풀스택 과정 61일차 (0) | 2024.10.22 |
JSP 설정 및 기초 - AWS 풀스택 과정 60일차 (0) | 2024.10.21 |