일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- 자바
- 환경설정
- oracle
- EnhancedFor
- 메소드오버로딩
- exception
- 예외미루기
- 컬렉션 타입
- 제네릭
- GRANT VIEW
- 생성자오버로드
- 객체 비교
- 예외처리
- abstract
- 어윈 사용법
- 추상메서드
- 참조형변수
- 자동차수리시스템
- NestedFor
- cursor문
- 정수형타입
- 집합_SET
- 다형성
- 사용자예외클래스생성
- 오라클
- 한국건설관리시스템
- Java
- 인터페이스
- 대덕인재개발원
- 컬렉션프레임워크
- Today
- Total
거니의 velog
231005_고급자바과제_회원정보관리 본문
MYMEMBER테이블에 'MEM_PHOTO' 컬럼 추가 후 작업
회원목록 출력(memberList) ==> 회원추가버튼 클릭 ==> 회원추가 폼 (자료입력) ==> 저장버튼 클릭 ==> 회원정보 Insert ==> 회원목록 출력(memberList)로 이동
회원목록 출력(memberList) ==> 회원ID 클릭 ==> 해당 회원의 상세정보 출력 ( 수정버튼과 삭제버튼이 있다.)
회원상세정보 ==> 수정버튼 클릭 ==> 회원 수정 폼 출력 ( 자료 수정 ) ==> 저장버튼 클릭 ==> 회원 정보 Update ==> 회원목록 출력(memberList)로 이동
회원상세정보 ==> 삭제버튼 클릭 ==> 회원정보 delete ==> 회원목록 출력(memberList)로 이동
[MemberVO.java]
package kr.or.ddit.vo;
public class MemberVO {
private String mem_id;
private String mem_pass;
private String mem_name;
private String mem_tel;
private String mem_addr;
private String mem_photo;
public MemberVO() {}
public MemberVO(String mem_id, String mem_pass, String mem_name, String mem_tel, String mem_addr,
String mem_photo) {
this.mem_id = mem_id;
this.mem_pass = mem_pass;
this.mem_name = mem_name;
this.mem_tel = mem_tel;
this.mem_addr = mem_addr;
this.mem_photo = mem_photo;
}
public String getMem_id() {
return mem_id;
}
public void setMem_id(String mem_id) {
this.mem_id = mem_id;
}
public String getMem_pass() {
return mem_pass;
}
public void setMem_pass(String mem_pass) {
this.mem_pass = mem_pass;
}
public String getMem_name() {
return mem_name;
}
public void setMem_name(String mem_name) {
this.mem_name = mem_name;
}
public String getMem_tel() {
return mem_tel;
}
public void setMem_tel(String mem_tel) {
this.mem_tel = mem_tel;
}
public String getMem_addr() {
return mem_addr;
}
public void setMem_addr(String mem_addr) {
this.mem_addr = mem_addr;
}
public String getMem_photo() {
return mem_photo;
}
public void setMem_photo(String mem_photo) {
this.mem_photo = mem_photo;
}
@Override
public String toString() {
return "MemberVO [mem_id=" + mem_id + ", mem_pass=" + mem_pass + ", mem_name=" + mem_name + ", mem_tel="
+ mem_tel + ", mem_addr=" + mem_addr + ", mem_photo=" + mem_photo + "]";
}
}
[mybatis-config.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org/DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- DB연결 정보가 저장된 properties파일에 대한 정보를 설정한다. -->
<properties resource="kr/or/ddit/mybatis/config/dbinfo.properties" />
<!-- MyBatis 설정과 관련된 기본 setting 설정 -->
<settings>
<!-- 데이터가 null로 전달되었으면 빈칸으로 인식하지 말고 null로 인식하라 -->
<setting name="jdbcTypeForNull" value="NULL" />
</settings>
<typeAliases>
<typeAlias type="kr.or.ddit.vo.MemberVO" alias="memVo" />
<typeAlias type="kr.or.ddit.vo.LprodVO" alias="lprodVo" />
<typeAlias type="kr.or.ddit.vo.FileInfoVO" alias="fileVo" />
</typeAliases>
<!-- DB연결 설정 -->
<environments default="oracleDev">
<environment id="oracleDev">
<!-- 오라클 -->
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
</dataSource>
</environment>
<!-- <environment id="m1">
MySql
</environment> -->
</environments>
<mappers>
<mapper resource="kr/or/ddit/mybatis/mappers/member-mapper.xml" />
<mapper resource="kr/or/ddit/mybatis/mappers/lprod-mapper.xml" />
<mapper resource="kr/or/ddit/mybatis/mappers/fileinfo-mapper.xml" />
</mappers>
</configuration>
[member-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="member">
<select id="getMemberList" resultType="memVo">
select * from mymember
</select>
<insert id="insertMember" parameterType="memVo">
INSERT INTO mymember (mem_id, mem_pass, mem_name, mem_tel, mem_addr, mem_photo)
VALUES (#{mem_id}, #{mem_pass}, #{mem_name}, #{mem_tel}, #{mem_addr}, #{mem_photo})
</insert>
</mapper>
[IMemberDAO.java]
package kr.or.ddit.member.dao;
import java.util.List;
import kr.or.ddit.vo.MemberVO;
public interface IMemberDAO {
public List<MemberVO> getMemberList();
public int insertMember(MemberVO mvo);
}
[MemberDaoImpl.java]
package kr.or.ddit.member.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.MemberVO;
public class MemberDaoImpl implements IMemberDAO {
private static MemberDaoImpl dao;
private MemberDaoImpl() {}
public static MemberDaoImpl getInstance() {
if(dao == null) dao = new MemberDaoImpl();
return dao;
}
@Override
public List<MemberVO> getMemberList() {
SqlSession session = MyBatisUtil.getSqlSession();
List<MemberVO> memberList = null;
try {
memberList = session.selectList("member.getMemberList");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return memberList;
}
@Override
public int insertMember(MemberVO mvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.insert("member.insertMember", mvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
}
[IMemberService.java]
package kr.or.ddit.member.service;
import java.util.List;
import kr.or.ddit.vo.MemberVO;
public interface IMemberService {
public List<MemberVO> getMemberList();
public int insertMember(MemberVO mvo);
}
[MemberServiceImpl.java]
package kr.or.ddit.member.service;
import java.util.List;
import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.vo.MemberVO;
public class MemberServiceImpl implements IMemberService {
private IMemberDAO dao;
private static MemberServiceImpl service;
private MemberServiceImpl() {
dao = MemberDaoImpl.getInstance();
}
public static MemberServiceImpl getInstance() {
if(service == null) service = new MemberServiceImpl();
return service;
}
@Override
public List<MemberVO> getMemberList() {
return dao.getMemberList();
}
@Override
public int insertMember(MemberVO mvo) {
return dao.insertMember(mvo);
}
}
[memberMain.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>회원정보 보기</title>
</head>
<body>
<a href="<%= request.getContextPath() %>/memberList.do">회원 목록 보기</a>
</body>
</html>
[MemberList.java]
package kr.or.ddit.member.controller;
import java.io.IOException;
import java.util.List;
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 kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.vo.MemberVO;
@WebServlet("/memberList.do")
public class MemberList extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
IMemberService service = MemberServiceImpl.getInstance();
// 멤버 전체 목록 가져오기
List<MemberVO> memberList = service.getMemberList();
// 가져온 전체 목록을 View로 보낸다.
request.setAttribute("memberList", memberList);
request.getRequestDispatcher("/basic/meminfo/memberList.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
[memberList.jsp]
<%@page import="kr.or.ddit.vo.MemberVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원 목록 보기</title>
</head>
<body>
<%
// 서블릿에서 보내온 자료 받기
List<MemberVO> memberList = (List<MemberVO>) request.getAttribute("memberList");
%>
<h2>회원 목록 보기</h2><br />
<table border="1">
<tr>
<td colspan="5" style="text-align: right;">
<button type="button" onclick="location.href='<%= request.getContextPath() %>/basic/meminfo/memberJoin.jsp';">회원추가</button>
</td>
</tr>
<tr>
<th>ID</th>
<th>비밀번호</th>
<th>이 름</th>
<th>전 화</th>
<th>주 소</th>
</tr>
<%
if(memberList == null || memberList.size() == 0) {
%>
<tr>
<td colspan="5">멤버 목록이 하나도 없습니다...</td>
</tr>
<%
}else{
for(MemberVO mvo : memberList) {
%>
<tr>
<td><a href="#none"><%= mvo.getMem_id() %></a></td>
<td><%= mvo.getMem_pass() %></td>
<td><%= mvo.getMem_name() %></td>
<td><%= mvo.getMem_tel() %></td>
<td><%= mvo.getMem_addr() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
- http://localhost:8090/webTest/basic/meminfo/memberMain.jsp
[member-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="member">
<select id="getMemberList" resultType="memVo">
select * from mymember
</select>
<insert id="insertMember" parameterType="memVo">
INSERT INTO mymember (mem_id, mem_pass, mem_name, mem_tel, mem_addr, mem_photo)
VALUES (#{mem_id}, #{mem_pass}, #{mem_name}, #{mem_tel}, #{mem_addr}, #{mem_photo})
</insert>
<select id="idDupChk" parameterType="String" resultType="String">
select mem_id from mymember where mem_id = #{mem_id}
</select>
</mapper>
[MemberDaoImpl.java]
package kr.or.ddit.member.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.MemberVO;
public class MemberDaoImpl implements IMemberDAO {
private static MemberDaoImpl dao;
private MemberDaoImpl() {}
public static MemberDaoImpl getInstance() {
if(dao == null) dao = new MemberDaoImpl();
return dao;
}
@Override
public List<MemberVO> getMemberList() {
SqlSession session = MyBatisUtil.getSqlSession();
List<MemberVO> memberList = null;
try {
memberList = session.selectList("member.getMemberList");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return memberList;
}
@Override
public int insertMember(MemberVO mvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.insert("member.insertMember", mvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public String idDupChk(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
String idChk = null;
try {
idChk = session.selectOne("member.idDupChk", memid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return idChk;
}
}
[MemberServiceImpl.java]
package kr.or.ddit.member.service;
import java.util.List;
import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.vo.MemberVO;
public class MemberServiceImpl implements IMemberService {
private IMemberDAO dao;
private static MemberServiceImpl service;
private MemberServiceImpl() {
dao = MemberDaoImpl.getInstance();
}
public static MemberServiceImpl getInstance() {
if(service == null) service = new MemberServiceImpl();
return service;
}
@Override
public List<MemberVO> getMemberList() {
return dao.getMemberList();
}
@Override
public int insertMember(MemberVO mvo) {
return dao.insertMember(mvo);
}
@Override
public String idDupChk(String memid) {
return dao.idDupChk(memid);
}
}
[memberJoin.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>회원 정보 입력 폼</title>
<style type="text/css">
th {
text-align: left;
}
</style>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
<script>
$(function(){
var idDupFlag = false; // 아이디 중복 체크 값
$("#userid").keyup(function(){
var dupmsg = $("#dupMsg");
dupmsg.text("");
var thisIs = $(this);
var idVal = thisIs.val().trim();
$.ajax({
url : "<%= request.getContextPath() %>/idDupChk.do",
data : { "idVal" : idVal },
type : "post",
success : function(res){
if(thisIs.val() == ""){
dupmsg.text("");
}else {
if(!res){
dupmsg.text("id사용가능");
dupmsg.css("color", "lightgreen");
}else {
dupmsg.text("id중복");
dupmsg.css("color", "red");
}
}
},
error : function(xhr){
alert("상태 : " + xhr.status);
},
dataType : "json"
});
thisIs.val(idVal);
});
});
</script>
</head>
<body>
<h2>회원 정보 입력 폼</h2><br />
<form>
<table border="1">
<tr>
<th>회원 ID</th>
<td>
<input id="userid" name="userid" type="text" />
<!-- <button id="idDupChk" type="button">중복확인</button> -->
<span id="dupMsg"></span>
</td>
</tr>
<tr>
<th>비밀번호</th>
<td>
<input id="userpw" name="userpw" type="password" />
</td>
</tr>
<tr>
<th>비밀번호 확인</th>
<td>
<input id="userpwchk" name="userpwchk" type="password" />
<button id="passDupChk" type="button">중복확인</button>
</td>
</tr>
<tr>
<th>회원이름</th>
<td>
<input id="usernm" name="usernm" type="text" />
</td>
</tr>
<tr>
<th>전화번호</th>
<td>
<input id="userhp" name="userhp" type="text" />
</td>
</tr>
<tr>
<th>회원주소</th>
<td>
<input id="useraddr" name="useraddr" type="text" />
</td>
</tr>
<tr>
<th>프로필 사진</th>
<td>
<input id="userprofile" name="userprofile" type="file" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<button type="submit">저장</button>
<button type="reset">취소</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</form>
</body>
</html>
[IdDupChk.java]
package kr.or.ddit.member.controller;
import java.io.IOException;
import java.io.PrintWriter;
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 com.google.gson.Gson;
import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
@WebServlet("/idDupChk.do")
public class IdDupChk extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = response.getWriter();
String idVal = request.getParameter("idVal");
IMemberDAO dao = MemberDaoImpl.getInstance();
String idChk = dao.idDupChk(idVal);
Gson gson = new Gson();
String jsonData = gson.toJson(idChk);
out.write(jsonData);
response.flushBuffer();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- http://localhost:8090/webTest/basic/meminfo/memberJoin.jsp
[memberJoin.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>회원 정보 입력 폼</title>
<style type="text/css">
th {
text-align: left;
}
</style>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
<script>
$(function(){
var idDupFlag = false; // 아이디 중복 체크 값
var passChkFlag = false; // 비밀번호 중복 체크 값
$("#userid").keyup(function(){
var dupmsg = $("#dupMsg");
dupmsg.text("");
var thisIs = $(this);
var idVal = thisIs.val().trim();
$.ajax({
url : "<%= request.getContextPath() %>/idDupChk.do",
data : { "idVal" : idVal },
type : "post",
success : function(res){
if(thisIs.val() == ""){
dupmsg.text("");
}else {
if(!res){
dupmsg.text("id사용가능");
dupmsg.css("color", "lightgreen");
}else {
dupmsg.text("id중복");
dupmsg.css("color", "red");
}
}
},
error : function(xhr){
alert("상태 : " + xhr.status);
},
dataType : "json"
});
thisIs.val(idVal);
}); // #userid 이벤트 끝...
$("#passDupChk").click(function(){
var passVal = $("#userpw").val();
var passDupVal = $("#userpwchk").val();
if(passVal == passDupVal){
alert("비밀번호가 일치합니다.");
passChkFlag = true;
}else{
alert("비밀번호가 일치하지 않습니다. 다시 입력해 주세요.");
passChkFlag = false;
}
}); // #passDupChk 이벤트 끝...
}); // ready() 끝...
</script>
</head>
<body>
<h2>회원 정보 입력 폼</h2><br />
<form>
<table border="1">
<tr>
<th>회원 ID</th>
<td>
<input id="userid" name="userid" type="text" />
<!-- <button id="idDupChk" type="button">중복확인</button> -->
<span id="dupMsg"></span>
</td>
</tr>
<tr>
<th>비밀번호</th>
<td>
<input id="userpw" name="userpw" type="password" />
</td>
</tr>
<tr>
<th>비밀번호 확인</th>
<td>
<input id="userpwchk" name="userpwchk" type="password" />
<button id="passDupChk" type="button">중복확인</button>
</td>
</tr>
<tr>
<th>회원이름</th>
<td>
<input id="usernm" name="usernm" type="text" />
</td>
</tr>
<tr>
<th>전화번호</th>
<td>
<input id="userhp" name="userhp" type="text" />
</td>
</tr>
<tr>
<th>회원주소</th>
<td>
<input id="useraddr" name="useraddr" type="text" />
</td>
</tr>
<tr>
<th>프로필 사진</th>
<td>
<input id="userprofile" name="userprofile" type="file" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<button type="submit">저장</button>
<button type="reset">취소</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</form>
</body>
</html>
[memberJoin.jsp]
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>회원 정보 입력 폼</title>
<style type="text/css">
th {
text-align: left;
}
</style>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
<script>
$(function(){
var idDupFlag = false; // 아이디 중복 체크 값
var passChkFlag = false; // 비밀번호 중복 체크 값
$("#userid").keyup(function(){
var dupmsg = $("#dupMsg");
dupmsg.text("");
var thisIs = $(this);
var idVal = thisIs.val().trim();
$.ajax({
url : "<%= request.getContextPath() %>/idDupChk.do",
data : { "idVal" : idVal },
type : "post",
success : function(res){
if(thisIs.val() == ""){
dupmsg.text("");
}else {
if(!res){
dupmsg.text("id사용가능");
dupmsg.css("color", "lightgreen");
}else {
dupmsg.text("id중복");
dupmsg.css("color", "red");
}
}
},
error : function(xhr){
alert("상태 : " + xhr.status);
},
dataType : "json"
});
thisIs.val(idVal);
}); // #userid 이벤트 끝...
$("#passDupChk").click(function(){
var passVal = $("#userpw").val();
var passDupVal = $("#userpwchk").val();
if(passVal == passDupVal){
alert("비밀번호가 일치합니다.");
passChkFlag = true;
}else{
alert("비밀번호가 일치하지 않습니다. 다시 입력해 주세요.");
passChkFlag = false;
}
}); // #passDupChk 이벤트 끝...
$("#memJoinSubmit").click(function(){
if($("#dupMsg").text() == "id사용가능"){
idDupFlag = true;
}else {
idDupFlag = false;
}
// console.log(idDupFlag); - id중복체크
if(!idDupFlag){ // id 중복체크 안했다면..
alert("id를 확인해 주세요.");
return false;
}else if(!passChkFlag){ // 비밀번호 중복체크 안했다면...
alert("비밀번호 중복을 확인해 주세요.")
return false;
}else{
var userid = $("#userid");
var userpw = $("#userpw");
var usernm = $("#usernm");
var userhp = $("#userhp");
var useraddr = $("#useraddr");
var idVal = userid.val().trim(); // 빈 칸 없애기
userid.val(idVal);
var pwVal = userpw.val().trim();
userpw.val(pwVal);
var nmVal = usernm.val().trim();
usernm.val(nmVal);
var hpVal = userhp.val().trim();
userhp.val(hpVal);
var addrVal = useraddr.val().trim();
useraddr.val(addrVal);
if(!nmVal) {
alert("이름은 필수 입력입니다.");
usernm.focus();
return false;
}else if(!hpVal){
alert("전화번호는 필수 입력입니다.");
userhp.focus();
return false;
}else if(!addrVal){
alert("주소는 필수 입력입니다.");
useraddr.focus();
return false;
}else{
idVal = userid.val().trim(); // 빈 칸 없애기
userid.val(idVal);
pwVal = userpw.val().trim();
userpw.val(pwVal);
nmVal = usernm.val().trim();
usernm.val(nmVal);
hpVal = userhp.val().trim();
userhp.val(hpVal);
addrVal = useraddr.val().trim();
useraddr.val(addrVal);
$("#memjoinForm").submit();
}
}
}); // #memJoinSubmit 끝
}); // ready() 끝...
</script>
</head>
<body>
<h2>회원 정보 입력 폼</h2><br />
<form id="memjoinForm" action="<%= request.getContextPath() %>/memJoin.do" method="post" enctype="multipart/form-data">
<table border="1">
<tr>
<th>회원 ID</th>
<td>
<input id="userid" name="userid" type="text" />
<!-- <button id="idDupChk" type="button">중복확인</button> -->
<span id="dupMsg"></span>
</td>
</tr>
<tr>
<th>비밀번호</th>
<td>
<input id="userpw" name="userpw" type="password" />
</td>
</tr>
<tr>
<th>비밀번호 확인</th>
<td>
<input id="userpwchk" name="userpwchk" type="password" />
<button id="passDupChk" type="button">중복확인</button>
</td>
</tr>
<tr>
<th>회원이름</th>
<td>
<input id="usernm" name="usernm" type="text" />
</td>
</tr>
<tr>
<th>전화번호</th>
<td>
<input id="userhp" name="userhp" type="text" />
</td>
</tr>
<tr>
<th>회원주소</th>
<td>
<input id="useraddr" name="useraddr" type="text" />
</td>
</tr>
<tr>
<th>프로필 사진</th>
<td>
<input id="userprofile" name="userprofile" type="file" />
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<button id="memJoinSubmit" type="button">저장</button>
<button type="reset">취소</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</form>
</body>
</html>
[MemJoin.java]
package kr.or.ddit.member.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import kr.or.ddit.fileupload.service.FileInfoServiceImpl;
import kr.or.ddit.fileupload.service.IFileInfoService;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.vo.FileInfoVO;
import kr.or.ddit.vo.MemberVO;
@WebServlet("/memJoin.do")
@MultipartConfig
public class MemJoin extends HttpServlet {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 클라이언트가 보내온 일반 데이터 받기
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
String usernm = request.getParameter("usernm");
String userhp = request.getParameter("userhp");
String useraddr = request.getParameter("useraddr");
// 클라이언트가 보내온 이미지 데이터 받기
String uploadPath = "d:/webTest/images";
File f = new File(uploadPath);
if(!f.exists()) {
f.mkdirs();
}
String fileName = "";
List<FileInfoVO> fileList = new ArrayList<FileInfoVO>(); // 업로드할 파일 목록이 저장될 List 객체 생성
for(Part part : request.getParts()) {
fileName = extractFileName(part);
if(!"".equals(fileName)) { // 파일 여부 검사
FileInfoVO fvo = new FileInfoVO();
fvo.setFile_writer(usernm);
fvo.setOrigin_file_name(fileName);
String saveFileName = UUID.randomUUID().toString() + "_" + fileName;
fvo.setSave_file_name(saveFileName);
long filesize = (long) Math.ceil(part.getSize() / 1024.0);
fvo.setFile_size(filesize);
try {
part.write(uploadPath + File.separator + saveFileName);
} catch (Exception e) {
e.printStackTrace();
}
fileList.add(fvo);
}
}
IFileInfoService fileService = FileInfoServiceImpl.getInstance();
for(FileInfoVO fvo : fileList) {
fileService.insertFileInfo(fvo); // 파일 저장 완료.
}
IMemberService memService = MemberServiceImpl.getInstance();
MemberVO mvo = new MemberVO();
mvo.setMem_id(userid);
mvo.setMem_pass(userpw);
mvo.setMem_name(usernm);
mvo.setMem_tel(userhp);
mvo.setMem_addr(useraddr);
//System.out.println("fileList : " + fileList.toString());
int insCnt = 0;
if(fileList == null || fileList.size() == 0) {
//System.out.println("파일이 없어용");
mvo.setMem_photo(null);
insCnt = memService.insertMember(mvo);
}else{
//System.out.println("파일이 있어용");
// 저장된 파일 번호 가져오기
int intMaxFileNo = fileService.getFileNoMax();
String strMaxFileNo = String.valueOf(intMaxFileNo);
mvo.setMem_photo(strMaxFileNo);
insCnt = memService.insertMember(mvo);
}
if(insCnt > 0) {
response.sendRedirect(request.getContextPath() + "/memberList.do");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
// Part 구조 안에서 파일명을 찾는 메서드
// => 파일일 때는 '해당 파일명'을 반환하고, 파일이 아닐 때는 빈문자열("")을 반환한다.
public String extractFileName(Part part) {
String fileName = ""; // 반환값
String value = part.getHeader("content-disposition");
String[] items = value.split(";");
for(String item : items) {
if(item.trim().startsWith("filename")) {
fileName = item.substring(item.indexOf("=")+2, item.length()-1);
}
}
//System.out.println(fileName);
return fileName;
}
}
[fileinfo-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="fileinfo">
<insert id="insertFileInfo" parameterType="fileVo">
INSERT INTO fileinfo (file_no, file_writer, origin_file_name, save_file_name, file_size, file_date)
VALUES (fileinfo_seq.nextval, #{file_writer}, #{origin_file_name}, #{save_file_name}, #{file_size}, sysdate)
</insert>
<select id="getAllFileInfo" resultType="fileVo">
select * from fileinfo
</select>
<select id="getFileInfo" parameterType="int" resultType="fileVo">
select * from fileinfo where file_no = #{file_no}
</select>
<select id="getFileNoMax" resultType="int">
select max(file_no) from fileinfo
</select>
</mapper>
[FileInfoDaoImpl.java]
package kr.or.ddit.fileupload.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.FileInfoVO;
public class FileInfoDaoImpl implements IFileInfoDao {
private static FileInfoDaoImpl dao;
private FileInfoDaoImpl() {}
public static FileInfoDaoImpl getInstance() {
if(dao == null) dao = new FileInfoDaoImpl();
return dao;
}
@Override
public int insertFileInfo(FileInfoVO fvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0; // 반환값이 저장될 변수
try {
cnt = session.insert("fileinfo.insertFileInfo", fvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public List<FileInfoVO> getAllFileInfo() {
SqlSession session = MyBatisUtil.getSqlSession();
List<FileInfoVO> fileList = null; // 반환값이 저장될 변수
try {
fileList = session.selectList("fileinfo.getAllFileInfo");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileList;
}
@Override
public FileInfoVO getFileInfo(int fileNo) {
SqlSession session = MyBatisUtil.getSqlSession();
FileInfoVO fileVo = null; // 반환값이 저장될 변수
try {
fileVo = session.selectOne("fileinfo.getFileInfo", fileNo);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileVo;
}
@Override
public int getFileNoMax() {
SqlSession session = MyBatisUtil.getSqlSession();
int fileNoMax = 0;
try {
fileNoMax = session.selectOne("fileinfo.getFileNoMax");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileNoMax;
}
}
[FileInfoServiceImpl.java]
package kr.or.ddit.fileupload.service;
import java.util.List;
import kr.or.ddit.fileupload.dao.FileInfoDaoImpl;
import kr.or.ddit.fileupload.dao.IFileInfoDao;
import kr.or.ddit.vo.FileInfoVO;
public class FileInfoServiceImpl implements IFileInfoService {
private IFileInfoDao dao;
private static FileInfoServiceImpl service;
private FileInfoServiceImpl() {
dao = FileInfoDaoImpl.getInstance();
}
public static FileInfoServiceImpl getInstance() {
if(service == null) service = new FileInfoServiceImpl();
return service;
}
@Override
public int insertFileInfo(FileInfoVO fvo) {
return dao.insertFileInfo(fvo);
}
@Override
public List<FileInfoVO> getAllFileInfo() {
return dao.getAllFileInfo();
}
@Override
public FileInfoVO getFileInfo(int fileNo) {
return dao.getFileInfo(fileNo);
}
@Override
public int getFileNoMax() {
return dao.getFileNoMax();
}
}
- http://localhost:8090/webTest/memberList.do
[memberList.jsp]
<%@page import="kr.or.ddit.vo.MemberVO"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원 목록 보기</title>
</head>
<body>
<%
// 서블릿에서 보내온 자료 받기
List<MemberVO> memberList = (List<MemberVO>) request.getAttribute("memberList");
%>
<h2>회원 목록 보기</h2><br />
<table border="1">
<tr>
<td colspan="5" style="text-align: right;">
<button type="button" onclick="location.href='<%= request.getContextPath() %>/basic/meminfo/memberJoin.jsp';">회원추가</button>
</td>
</tr>
<tr>
<th>ID</th>
<th>비밀번호</th>
<th>이 름</th>
<th>전 화</th>
<th>주 소</th>
</tr>
<%
if(memberList == null || memberList.size() == 0) {
%>
<tr>
<td colspan="5">멤버 목록이 하나도 없습니다...</td>
</tr>
<%
}else{
for(MemberVO mvo : memberList) {
%>
<tr>
<td><a href="<%= request.getContextPath() %>/memInfo.do?memid=<%= mvo.getMem_id() %>"><%= mvo.getMem_id() %></a></td>
<td><%= mvo.getMem_pass() %></td>
<td><%= mvo.getMem_name() %></td>
<td><%= mvo.getMem_tel() %></td>
<td><%= mvo.getMem_addr() %></td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
[MemInfo.java]
package kr.or.ddit.member.controller;
import java.io.IOException;
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 kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.vo.MemberVO;
@WebServlet("/memInfo.do")
public class MemInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String memid = request.getParameter("memid");
IMemberService service = MemberServiceImpl.getInstance();
MemberVO mvo = service.selectFromMemid(memid);
request.setAttribute("mvo", mvo);
request.getRequestDispatcher("/basic/meminfo/memInfo.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
[memInfo.jsp]
<%@page import="kr.or.ddit.vo.MemberVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원정보상세</title>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
</head>
<body>
<%
MemberVO mvo = (MemberVO) request.getAttribute("mvo");
%>
<h2>회원 정보 상세보기</h2><br />
<table border="1">
<tr>
<td colspan="2">
<%
if(mvo.getMem_photo() == null){
%>
<img src="<%= request.getContextPath() %>/images/default_profile.png" />
<%
}else{
%>
<img src="<%= request.getContextPath() %>/images/memberView.do?fileno=<%= mvo.getMem_photo() %>" />
<%
}
%>
</td>
</tr>
<%
if(mvo == null) { // 회원 정보가 없을 때
%>
<tr>
<th colspan="2">등록된 회원 정보가 없습니다...</th>
</tr>
<%
}else{ // 회원 정보가 있을 때
%>
<tr>
<td>회원ID</td>
<td><%= mvo.getMem_id() %></td>
</tr>
<tr>
<td>비밀번호</td>
<td><%= mvo.getMem_pass() %></td>
</tr>
<tr>
<td>회원이름</td>
<td><%= mvo.getMem_name() %></td>
</tr>
<tr>
<td>전화번호</td>
<td><%= mvo.getMem_tel() %></td>
</tr>
<tr>
<td>회원주소</td>
<td><%= mvo.getMem_addr() %></td>
</tr>
<%
}
%>
<tr>
<td colspan="2" style="text-align: center;">
<button id="modityMem" type="button">수정</button>
<button id="removeMem" type="button">삭제</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</body>
</html>
[MemberView.java]
package kr.or.ddit.member.controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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 kr.or.ddit.fileupload.service.FileInfoServiceImpl;
import kr.or.ddit.fileupload.service.IFileInfoService;
import kr.or.ddit.vo.FileInfoVO;
@WebServlet("/images/memberView.do")
public class MemberView extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 파라미터로 넘어 온 파일 번호를 구한다.
String strFileNo = request.getParameter("fileno");
int fileno = Integer.parseInt(strFileNo);
// 파일 번호를 이용하여 DB에서 해당 파일 정보를 가져온다.
IFileInfoService service = FileInfoServiceImpl.getInstance();
FileInfoVO fvo = service.getFileInfo(fileno);
// 업로드 된 파일이 저장될 폴더 설정
String uploadPath = "d:/webTest/images";
// 지정된 폴더가 없으면 새로 만든다.
File f = new File(uploadPath);
if(!f.exists()) {
f.mkdirs();
}
File downFile = new File(f, fvo.getSave_file_name());
if(downFile.exists()) {
// 자바의 입출력 스트림을 이용해서 서버에 있는 파일을 읽어서 클라이언트로 출력하는
// 작업을 진행하면 된다.
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
// 출력용 스트림 객체 생성 (Response객체를 이용한다.)
bout = new BufferedOutputStream(response.getOutputStream());
// 파일 입력용 스트림 객체 생성
bin = new BufferedInputStream(new FileInputStream(downFile));
byte[] temp = new byte[1024];
int len = 0;
while( (len = bin.read(temp)) > 0 ) {
bout.write(temp, 0, len);
}
bout.flush();
} catch (Exception e) {
System.out.println("파일 입출력 오류 : " + e.getMessage());
} finally {
if(bin != null) try { bin.close(); } catch (Exception e) {}
if(bout != null) try { bout.close(); } catch (Exception e) {}
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- http://localhost:8090/webTest/memberList.do
[fileinfo-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="fileinfo">
<insert id="insertFileInfo" parameterType="fileVo">
INSERT INTO fileinfo (file_no, file_writer, origin_file_name, save_file_name, file_size, file_date)
VALUES (fileinfo_seq.nextval, #{file_writer}, #{origin_file_name}, #{save_file_name}, #{file_size}, sysdate)
</insert>
<select id="getAllFileInfo" resultType="fileVo">
select * from fileinfo
</select>
<select id="getFileInfo" parameterType="int" resultType="fileVo">
select * from fileinfo where file_no = #{file_no}
</select>
<select id="getFileNoMax" resultType="int">
select max(file_no) from fileinfo
</select>
<delete id="deleteFile" parameterType="int">
DELETE FROM fileinfo
WHERE file_no = #{file_no}
</delete>
</mapper>
[FileInfoDaoImpl.java]
package kr.or.ddit.fileupload.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.FileInfoVO;
public class FileInfoDaoImpl implements IFileInfoDao {
private static FileInfoDaoImpl dao;
private FileInfoDaoImpl() {}
public static FileInfoDaoImpl getInstance() {
if(dao == null) dao = new FileInfoDaoImpl();
return dao;
}
@Override
public int insertFileInfo(FileInfoVO fvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0; // 반환값이 저장될 변수
try {
cnt = session.insert("fileinfo.insertFileInfo", fvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public List<FileInfoVO> getAllFileInfo() {
SqlSession session = MyBatisUtil.getSqlSession();
List<FileInfoVO> fileList = null; // 반환값이 저장될 변수
try {
fileList = session.selectList("fileinfo.getAllFileInfo");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileList;
}
@Override
public FileInfoVO getFileInfo(int fileNo) {
SqlSession session = MyBatisUtil.getSqlSession();
FileInfoVO fileVo = null; // 반환값이 저장될 변수
try {
fileVo = session.selectOne("fileinfo.getFileInfo", fileNo);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileVo;
}
@Override
public int getFileNoMax() {
SqlSession session = MyBatisUtil.getSqlSession();
int fileNoMax = 0;
try {
fileNoMax = session.selectOne("fileinfo.getFileNoMax");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return fileNoMax;
}
@Override
public int deleteFile(int fileNo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.delete("fileinfo.deleteFile", fileNo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
}
[FileInfoServiceImpl.java]
package kr.or.ddit.fileupload.service;
import java.util.List;
import kr.or.ddit.fileupload.dao.FileInfoDaoImpl;
import kr.or.ddit.fileupload.dao.IFileInfoDao;
import kr.or.ddit.vo.FileInfoVO;
public class FileInfoServiceImpl implements IFileInfoService {
private IFileInfoDao dao;
private static FileInfoServiceImpl service;
private FileInfoServiceImpl() {
dao = FileInfoDaoImpl.getInstance();
}
public static FileInfoServiceImpl getInstance() {
if(service == null) service = new FileInfoServiceImpl();
return service;
}
@Override
public int insertFileInfo(FileInfoVO fvo) {
return dao.insertFileInfo(fvo);
}
@Override
public List<FileInfoVO> getAllFileInfo() {
return dao.getAllFileInfo();
}
@Override
public FileInfoVO getFileInfo(int fileNo) {
return dao.getFileInfo(fileNo);
}
@Override
public int getFileNoMax() {
return dao.getFileNoMax();
}
@Override
public int deleteFile(int fileNo) {
return dao.deleteFile(fileNo);
}
}
[member-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="member">
<select id="getMemberList" resultType="memVo">
select * from mymember
</select>
<insert id="insertMember" parameterType="memVo">
INSERT INTO mymember (mem_id, mem_pass, mem_name, mem_tel, mem_addr, mem_photo)
VALUES (#{mem_id}, #{mem_pass}, #{mem_name}, #{mem_tel}, #{mem_addr}, #{mem_photo})
</insert>
<select id="idDupChk" parameterType="String" resultType="String">
select mem_id from mymember where mem_id = #{mem_id}
</select>
<select id="selectFromMemid" parameterType="String" resultType="memVo">
select * from mymember where mem_id = #{mem_id}
</select>
<delete id="deleteMember" parameterType="String">
delete from mymember
where mem_id = #{mem_id}
</delete>
</mapper>
[MemberDaoImpl.java]
package kr.or.ddit.member.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.MemberVO;
public class MemberDaoImpl implements IMemberDAO {
private static MemberDaoImpl dao;
private MemberDaoImpl() {}
public static MemberDaoImpl getInstance() {
if(dao == null) dao = new MemberDaoImpl();
return dao;
}
@Override
public List<MemberVO> getMemberList() {
SqlSession session = MyBatisUtil.getSqlSession();
List<MemberVO> memberList = null;
try {
memberList = session.selectList("member.getMemberList");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return memberList;
}
@Override
public int insertMember(MemberVO mvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.insert("member.insertMember", mvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public String idDupChk(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
String idChk = null;
try {
idChk = session.selectOne("member.idDupChk", memid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return idChk;
}
@Override
public MemberVO selectFromMemid(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
MemberVO mvo = null;
try {
mvo = session.selectOne("member.selectFromMemid", memid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return mvo;
}
@Override
public int deleteMember(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.delete("member.deleteMember", memid);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
}
[MemberServiceImpl.java]
package kr.or.ddit.member.service;
import java.util.List;
import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.vo.MemberVO;
public class MemberServiceImpl implements IMemberService {
private IMemberDAO dao;
private static MemberServiceImpl service;
private MemberServiceImpl() {
dao = MemberDaoImpl.getInstance();
}
public static MemberServiceImpl getInstance() {
if(service == null) service = new MemberServiceImpl();
return service;
}
@Override
public List<MemberVO> getMemberList() {
return dao.getMemberList();
}
@Override
public int insertMember(MemberVO mvo) {
return dao.insertMember(mvo);
}
@Override
public String idDupChk(String memid) {
return dao.idDupChk(memid);
}
@Override
public MemberVO selectFromMemid(String memid) {
return dao.selectFromMemid(memid);
}
@Override
public int deleteMember(String memid) {
return dao.deleteMember(memid);
}
}
[MemberDelete.java]
package kr.or.ddit.member.controller;
import java.io.File;
import java.io.IOException;
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 kr.or.ddit.fileupload.service.FileInfoServiceImpl;
import kr.or.ddit.fileupload.service.IFileInfoService;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.vo.FileInfoVO;
@WebServlet("/memberDelete.do")
public class MemberDelete extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String memid = request.getParameter("memid");
String strfileno = request.getParameter("fileno");
//System.out.println("memid : " + memid);
//System.out.println("strfileno : " + strfileno);
if(!("null".equals(strfileno))) {
//System.out.println("null이 스트링타입이에용");
int fileNo = Integer.parseInt(strfileno);
IFileInfoService fileService = FileInfoServiceImpl.getInstance();
FileInfoVO fvo = fileService.getFileInfo(fileNo);
int delFile = fileService.deleteFile(fileNo);
if(delFile > 0) {
System.out.println("파일이 삭제되었습니다.");
}else {
System.out.println("파일을 찾을 수 없어 삭제하지 못했습니다.");
}
String uploadPath = "d:/webTest/images/";
String uploadimg = String.valueOf(fvo.getSave_file_name());
File f = new File(uploadPath + uploadimg);
if(f.exists()) { // 파일 존재 여부 확인
f.delete();
System.out.println("진짜 물리적 파일도 삭제되었습니다.");
}
}
IMemberService memberService = MemberServiceImpl.getInstance();
int delMem = memberService.deleteMember(memid);
if(delMem > 0) {
System.out.println("멤버 정보가 삭제되었습니다.");
}else {
System.out.println("멤버 정보를 삭제하지 못했습니다.");
}
response.sendRedirect(request.getContextPath() + "/memberList.do");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- http://localhost:8090/webTest/memberList.do
[memInfo.jsp]
<%@page import="kr.or.ddit.vo.MemberVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원정보상세</title>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
</head>
<body>
<%
MemberVO mvo = (MemberVO) request.getAttribute("mvo");
%>
<h2>회원 정보 상세보기</h2><br />
<table border="1">
<tr>
<td colspan="2">
<%
if(mvo.getMem_photo() == null){
%>
<img src="<%= request.getContextPath() %>/images/default_profile.png" />
<%
}else{
%>
<img src="<%= request.getContextPath() %>/images/memberView.do?fileno=<%= mvo.getMem_photo() %>" />
<%
}
%>
</td>
</tr>
<%
if(mvo == null) { // 회원 정보가 없을 때
%>
<tr>
<th colspan="2">등록된 회원 정보가 없습니다...</th>
</tr>
<%
}else{ // 회원 정보가 있을 때
%>
<tr>
<td>회원ID</td>
<td><%= mvo.getMem_id() %></td>
</tr>
<tr>
<td>비밀번호</td>
<td><%= mvo.getMem_pass() %></td>
</tr>
<tr>
<td>회원이름</td>
<td><%= mvo.getMem_name() %></td>
</tr>
<tr>
<td>전화번호</td>
<td><%= mvo.getMem_tel() %></td>
</tr>
<tr>
<td>회원주소</td>
<td><%= mvo.getMem_addr() %></td>
</tr>
<%
}
%>
<tr>
<td colspan="2" style="text-align: center;">
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberUpdate.do?memid=<%= mvo.getMem_id() %>&fileno=<%= mvo.getMem_photo() %>';">수정</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberDelete.do?memid=<%= mvo.getMem_id() %>&fileno=<%= mvo.getMem_photo() %>';">삭제</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</body>
</html>
[memberUpdate.jsp]
<%@page import="kr.or.ddit.vo.MemberVO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>회원 정보 수정</title>
<script src="<%= request.getContextPath() %>/js/jquery-3.7.1.min.js"></script>
<script>
$(function(){
$("#memUpdateBtn").click(function(){
var userid = $("#userid");
var userpw = $("#userpw");
var usernm = $("#usernm");
var userhp = $("#userhp");
var useraddr = $("#useraddr");
var idVal = userid.val().trim();
userid.val(idVal);
var pwVal = userpw.val().trim();
userpw.val(pwVal);
var nmVal = usernm.val().trim();
usernm.val(nmVal);
var hpVal = userhp.val().trim();
userhp.val(hpVal);
var addrVal = useraddr.val().trim();
useraddr.val(addrVal);
if(!nmVal) {
alert("이름은 필수 입력입니다.");
usernm.focus();
return false;
}else if(!hpVal){
alert("전화번호는 필수 입력입니다.");
userhp.focus();
return false;
}else if(!addrVal){
alert("주소는 필수 입력입니다.");
useraddr.focus();
return false;
}else if(!pwVal){
alert("비밀번호를 입력해 주세요.")
userpw.focus();
return false;
}else{
idVal = userid.val().trim(); // 빈 칸 없애기
userid.val(idVal);
pwVal = userpw.val().trim();
userpw.val(pwVal);
nmVal = usernm.val().trim();
usernm.val(nmVal);
hpVal = userhp.val().trim();
userhp.val(hpVal);
addrVal = useraddr.val().trim();
useraddr.val(addrVal);
$("#memUpdateForm").submit();
}
}); // #memJoinSubmit 끝
});
</script>
</head>
<body>
<%
MemberVO mvo = (MemberVO) request.getAttribute("mvo");
%>
<h2>회원 정보 수정</h2><br />
<form id="memUpdateForm" action="<%= request.getContextPath() %>/memberUpdate.do" method="post" enctype="multipart/form-data">
<table border="1">
<tr>
<td colspan="2">
<%
if(mvo.getMem_photo() == null){
%>
<img src="<%= request.getContextPath() %>/images/default_profile.png" />
<%
}else{
%>
<img src="<%= request.getContextPath() %>/images/memberView.do?fileno=<%= mvo.getMem_photo() %>" />
<%
}
%>
</td>
</tr>
<%
if(mvo == null) { // 회원 정보가 없을 때
%>
<tr>
<th colspan="2">등록된 회원 정보가 없습니다...</th>
</tr>
<%
}else{ // 회원 정보가 있을 때
%>
<tr>
<td>회원ID</td>
<td>
<%= mvo.getMem_id() %>
</td>
</tr>
<tr>
<td>비밀번호</td>
<td>
<input id="userpw" type="password" name="userpw" />
</td>
</tr>
<tr>
<td>회원이름</td>
<td>
<input id="usernm" type="text" name="usernm" value="<%= mvo.getMem_name() %>" />
</td>
</tr>
<tr>
<td>전화번호</td>
<td>
<input id="userhp" type="text" name="userhp" value="<%= mvo.getMem_tel() %>" />
</td>
</tr>
<tr>
<td>회원주소</td>
<td>
<input id="useraddr" type="text" name="useraddr" value="<%= mvo.getMem_addr() %>" />
</td>
</tr>
<tr>
<td>프로필 사진</td>
<td>
<input id="userprofile" name="userprofile" type="file" />
</td>
</tr>
<%
}
%>
<tr>
<td colspan="2" style="text-align: center;">
<input id="userid" type="hidden" name="userid" value="<%= mvo.getMem_id() %>" />
<input id="fileno" type="hidden" name="fileno" value="<%= mvo.getMem_photo() %>" />
<button id="memUpdateBtn" type="button">저장</button>
<button type="reset">취소</button>
<button type="button" onclick="location.href='<%= request.getContextPath() %>/memberList.do';">회원목록</button>
</td>
</tr>
</table>
</form>
</body>
</html>
[member-mapper.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org/DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="member">
<select id="getMemberList" resultType="memVo">
select * from mymember
</select>
<insert id="insertMember" parameterType="memVo">
INSERT INTO mymember (mem_id, mem_pass, mem_name, mem_tel, mem_addr, mem_photo)
VALUES (#{mem_id}, #{mem_pass}, #{mem_name}, #{mem_tel}, #{mem_addr}, #{mem_photo})
</insert>
<select id="idDupChk" parameterType="String" resultType="String">
select mem_id from mymember where mem_id = #{mem_id}
</select>
<select id="selectFromMemid" parameterType="String" resultType="memVo">
select * from mymember where mem_id = #{mem_id}
</select>
<delete id="deleteMember" parameterType="String">
delete from mymember
where mem_id = #{mem_id}
</delete>
<update id="updateMember" parameterType="memVo">
update mymember
set mem_pass = #{mem_pass}, mem_name = #{mem_name}, mem_tel = #{mem_tel}, mem_addr = #{mem_addr}, mem_photo = #{mem_photo}
where mem_id = #{mem_id}
</update>
</mapper>
[MemberDaoImpl.java]
package kr.or.ddit.member.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import kr.or.ddit.util.MyBatisUtil;
import kr.or.ddit.vo.MemberVO;
public class MemberDaoImpl implements IMemberDAO {
private static MemberDaoImpl dao;
private MemberDaoImpl() {}
public static MemberDaoImpl getInstance() {
if(dao == null) dao = new MemberDaoImpl();
return dao;
}
@Override
public List<MemberVO> getMemberList() {
SqlSession session = MyBatisUtil.getSqlSession();
List<MemberVO> memberList = null;
try {
memberList = session.selectList("member.getMemberList");
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return memberList;
}
@Override
public int insertMember(MemberVO mvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.insert("member.insertMember", mvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public String idDupChk(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
String idChk = null;
try {
idChk = session.selectOne("member.idDupChk", memid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return idChk;
}
@Override
public MemberVO selectFromMemid(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
MemberVO mvo = null;
try {
mvo = session.selectOne("member.selectFromMemid", memid);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return mvo;
}
@Override
public int deleteMember(String memid) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.delete("member.deleteMember", memid);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
@Override
public int updateMember(MemberVO mvo) {
SqlSession session = MyBatisUtil.getSqlSession();
int cnt = 0;
try {
cnt = session.update("member.updateMember", mvo);
if(cnt > 0) session.commit();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(session != null) session.close();
}
return cnt;
}
}
[MemberServiceImpl.java]
package kr.or.ddit.member.service;
import java.util.List;
import kr.or.ddit.member.dao.IMemberDAO;
import kr.or.ddit.member.dao.MemberDaoImpl;
import kr.or.ddit.vo.MemberVO;
public class MemberServiceImpl implements IMemberService {
private IMemberDAO dao;
private static MemberServiceImpl service;
private MemberServiceImpl() {
dao = MemberDaoImpl.getInstance();
}
public static MemberServiceImpl getInstance() {
if(service == null) service = new MemberServiceImpl();
return service;
}
@Override
public List<MemberVO> getMemberList() {
return dao.getMemberList();
}
@Override
public int insertMember(MemberVO mvo) {
return dao.insertMember(mvo);
}
@Override
public String idDupChk(String memid) {
return dao.idDupChk(memid);
}
@Override
public MemberVO selectFromMemid(String memid) {
return dao.selectFromMemid(memid);
}
@Override
public int deleteMember(String memid) {
return dao.deleteMember(memid);
}
@Override
public int updateMember(MemberVO mvo) {
return dao.updateMember(mvo);
}
}
[MemberUpdate.java]
package kr.or.ddit.member.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import kr.or.ddit.fileupload.service.FileInfoServiceImpl;
import kr.or.ddit.fileupload.service.IFileInfoService;
import kr.or.ddit.member.service.IMemberService;
import kr.or.ddit.member.service.MemberServiceImpl;
import kr.or.ddit.vo.FileInfoVO;
import kr.or.ddit.vo.MemberVO;
@WebServlet("/memberUpdate.do")
@MultipartConfig
public class MemberUpdate extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String memid = request.getParameter("memid");
IMemberService service = MemberServiceImpl.getInstance();
MemberVO mvo = service.selectFromMemid(memid);
request.setAttribute("mvo", mvo);
request.getRequestDispatcher("/basic/meminfo/memberUpdate.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
// 클라이언트가 보내온 일반 데이터 받기
String userid = request.getParameter("userid");
String userpw = request.getParameter("userpw");
String usernm = request.getParameter("usernm");
String userhp = request.getParameter("userhp");
String useraddr = request.getParameter("useraddr");
String strfileno = request.getParameter("fileno");
//System.out.println("일반 파라미터 데이터1 : " + userid + userpw + usernm);
//System.out.println("일반 파라미터 데이터2 : " + userhp + useraddr + strfileno);
// 클라이언트가 보내온 이미지 데이터 받기
String uploadPath = "d:/webTest/images";
File f = new File(uploadPath);
if(!f.exists()) {
f.mkdirs();
}
String fileName = "";
List<FileInfoVO> fileList = new ArrayList<FileInfoVO>(); // 업데이트할 파일 목록이 저장될 List 객체 생성
for(Part part : request.getParts()) {
fileName = extractFileName(part);
if(!"".equals(fileName)) { // 파일 여부 검사
FileInfoVO fvo = new FileInfoVO();
fvo.setFile_writer(usernm);
fvo.setOrigin_file_name(fileName);
String saveFileName = UUID.randomUUID().toString() + "_" + fileName;
fvo.setSave_file_name(saveFileName);
long filesize = (long) Math.ceil(part.getSize() / 1024.0);
fvo.setFile_size(filesize);
try {
part.write(uploadPath + File.separator + saveFileName);
} catch (Exception e) {
e.printStackTrace();
}
fileList.add(fvo);
}
}
IFileInfoService fileService = FileInfoServiceImpl.getInstance();
for(FileInfoVO fvo : fileList) {
fileService.insertFileInfo(fvo); // 파일 저장 완료.
}
IMemberService memService = MemberServiceImpl.getInstance();
MemberVO mvo = new MemberVO();
mvo.setMem_id(userid);
mvo.setMem_pass(userpw);
mvo.setMem_name(usernm);
mvo.setMem_tel(userhp);
mvo.setMem_addr(useraddr);
int updCnt = 0;
if(fileList == null || fileList.size() == 0) {
//System.out.println("파일이 없어용");
mvo.setMem_photo(strfileno);
updCnt = memService.updateMember(mvo);
}else{
//System.out.println("파일이 있어용");
if(!("null".equals(strfileno))) {
int fileNo = Integer.parseInt(strfileno);
FileInfoVO fvo = fileService.getFileInfo(fileNo);
int delFile = fileService.deleteFile(fileNo);
if(delFile > 0) {
System.out.println("파일이 삭제되었습니다.");
}else {
System.out.println("파일을 찾을 수 없어 삭제하지 못했습니다.");
}
String deletePath = "d:/webTest/images/";
String deleteImg = String.valueOf(fvo.getSave_file_name());
File f2 = new File(deletePath + deleteImg);
if(f2.exists()) { // 파일 존재 여부 확인
f2.delete();
System.out.println("진짜 물리적 파일도 삭제되었습니다.");
}
}
// 저장된 파일 번호 가져오기
int intMaxFileNo = fileService.getFileNoMax();
String strMaxFileNo = String.valueOf(intMaxFileNo);
mvo.setMem_photo(strMaxFileNo);
updCnt = memService.updateMember(mvo);
}
if(updCnt > 0) {
response.sendRedirect(request.getContextPath() + "/memberList.do");
}
}
public String extractFileName(Part part) {
String fileName = ""; // 반환값
String value = part.getHeader("content-disposition");
String[] items = value.split(";");
for(String item : items) {
if(item.trim().startsWith("filename")) {
fileName = item.substring(item.indexOf("=")+2, item.length()-1);
}
}
//System.out.println(fileName);
return fileName;
}
}
- http://localhost:8090/webTest/memberList.do
'대덕인재개발원_자바기반 애플리케이션' 카테고리의 다른 글
231010_회원정보관리_문제풀이 (0) | 2023.10.10 |
---|---|
231010_Redmine (0) | 2023.10.10 |
231005_File 업로드, 다운로드 (0) | 2023.10.05 |
231005_JSON (0) | 2023.10.05 |
231004_유스케이스 다이어그램 작성 (0) | 2023.10.04 |