스프링22_프로필 업로드, 정보 수정, 경로 재설정, 암호화

charl hi·2022년 2월 16일
1

Spring

목록 보기
23/25

파일 업로드

join.jsp

<body>

	<%@ include file="/WEB-INF/views/common/header.jsp" %>
	
	<div id="div-main">
		<h1>회원가입 페이지</h1>
		
		<form action = "" method = "post" enctype="multipart/form-data">
	        아이디 : <input type = "text" name = "userId"/><br>
	        비밀번호 : <input type = "password" name = "userPwd"/><br>
	        닉네임 : <input type = "text" name = "userNick"/><br>
	        나이 : <input type = "number" min="0" name = "userAge"/><br>
	        성별 : 
	        <select name="userGender">
	        	<option value="m">남자</option>
	        	<option value="f">여자</option>
	        </select><br>
	        사진 : <input type = "file" name = "f" multiple="multiple" accept=".jpg, .png"/><br>
	        <img id="profileImg"><br><hr>
	        <div id="div-preview">
	        
	        </div>
	        <input type = "submit" value ="회원가입"/>
	    </form>
	    
	    <hr><hr><hr>
	    
	</div>
	
	<script type="text/javascript">
	
		let fileTag = document.querySelector("input[name=f]");
		let divPreview = document.querySelector("#div-preview");
		
		fileTag.onchange = function(){
			
			//파일 올렸을 때 : fileTag.files.length > 0
			if(fileTag.files.length>0){
				//이미지 src에 들어갈 데이터 구하기
				for(let i=0; i<fileTag.files.length; i++){
					let reader = new FileReader();
					reader.onload = function(data){
						let src = data.target.result;
						//이미지 태그를 만들어서 넣어줄거임
						//1. 이미지 태그 만들기
						let imgTag = document.createElement('img');
						
						//2. 이미지 태그 속성들 세팅하기
						imgTag.setAttribute('src', src);
						imgTag.setAttribute('width', '100');
						imgTag.setAttribute('height', '100');
						
						//3. 이미지 태그 div안에 넣기
						divPreview.appendChild(imgTag);
					}
					reader.readAsDataURL(fileTag.files[i]);
					
				}//for end
				
			}else{
			//취소 버튼을 눌렀을 때
				//div 안에 싹 다 비우기
				divPreview.innerHTML = "";
			}
		}
	
	</script>

</body>



경로 재설정, 프로필 보이기, 마이페이지 연결

header.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<c:set var="root" value="${pageContext.request.contextPath}"/>

<link rel="stylesheet" href="${root}/resources/css/common/header.css">

	<div id="div-header">
		<table border="1">
			<tr>
				<td>빈칸</td>
				<td colspan="2"><a href="${root}"><img width="100%" height="50px" src="${pageContext.request.contextPath}/resources/imgs/qr.png"></a></td>
				<!-- href="/app999" -->
				<c:if test="${empty loginUser}">
					<td>빈칸</td>
				</c:if>
				<c:if test="${not empty loginUser}">
					<td><a href="${root}/member/mypage"><img src="${root}/resources/upload/profile/${loginUser.changeName}"></a></td>
				</c:if>
			</tr>
			<tr>
				<td><a href="${root}/notice/list">공지사항</a></td>
				<td>메뉴2</td>
				<td>메뉴3</td>
				<c:if test="${empty loginUser}">
					<td>
						<a href="${root}/member/login">로그인</a><br>
						<a href="${root}/member/join">회원가입</a>
					</td>
				</c:if>
				<c:if test="${not empty loginUser}">
					<td>
						${loginUser.userNick}님 환영합니다!<br>
						<a href="${root}/member/logout">로그아웃</a>
					</td>
				</c:if>
			</tr>
		</table>
	</div>


header.css

#div-header{
	width: 80vw;
	height: 20vh;
	margin:0 auto;
}

/* #div-header table tr td{
    cursor:pointer;
}
 */
#div-header table{
	width: 100%;
	height: 100%;
	text-align: center;
	margin:0 auto;
}

#div-header table tr:nth-child(1){
	height: 100px;
}
#div-header table tr:nth-child(2){
	height: 50px;
}

#div-main{
	width:80vw;
	margin: auto;
}

#div-header table img{
	height: 100px;
	width: 100px;
}



암호화, 수정

MemberController

@Controller
@RequestMapping("member")
public class MemberController {
	
	@Autowired
	private MemberService service;

	//로그인 화면 보여주기
	@GetMapping("login")
	public String login() {
		return "member/login";
	}
	
	//로그인 로직 처리
	@PostMapping("login")
	public String login(MemberDto dto, HttpSession session) throws Exception {
		MemberDto loginUser = service.login(dto);
		
		if(loginUser != null) {
			//success -> session에 담기 -> home으로
			session.setAttribute("loginUser", loginUser);
			return "redirect:/";
		}else {
			//fail -> login
			return "member/login";
		}
	}
	
	//회원가입 화면 보여주기
	@GetMapping("join")
	public String join() {
		return "member/join";
	}
	
	//회원가입 로직 처리
	@PostMapping("join")
	public String join(MemberDto dto, HttpServletRequest req) throws Exception {
		System.out.println(dto);
		
		int result = service.join(dto, req);
		
		if(result > 0) {
			return "redirect:/member/login";
		}else {
			return "redirect:/member/join";
		}
		
	}
	
	//로그아웃
	@GetMapping("logout")
	public String logout(HttpSession session) {
		//session 만료
		session.invalidate();
		return "redirect:/";
	}
	
	//마이페이지 화면 보여주기
	@GetMapping("mypage")
	public String mypage(HttpServletRequest req, HttpSession session) {
		MemberDto loginUser = (MemberDto) session.getAttribute("loginUser");
		if(loginUser == null) {
			req.setAttribute("msg", "로그인 하고 오세용!");
			
			return "error/errorPage";
		}
		return "member/mypage";
	}
	
	//마이페이지 내 정보 수정 로직 처리
	@PostMapping("mypage")
	public String mypage(MemberDto dto, HttpSession session) throws Exception {
		//update 처리하기
		MemberDto m = service.editMember(dto);
		if(m != null) {
			session.setAttribute("loginUser", m);
			return "redirect:/member/mypage";
		}else {
			//업데이트 실패
			return "redirect:/member/mypagezz";
			
		}
	}
}


MemberService

public interface MemberService {

	int join(MemberDto dto, HttpServletRequest req) throws Exception;

	MemberDto login(MemberDto dto) throws Exception;

	MemberDto editMember(MemberDto dto) throws Exception;
}


MemberServiceImpl

@Service
@Slf4j
@Transactional
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberDao dao;
	
	@Autowired
	private PasswordEncoder pe;
	
	@Override
	public int join(MemberDto dto, HttpServletRequest req) throws Exception{
		//회원가입 처리
		
		//회원번호, 시퀀스 nextval
		int no = dao.getMemberSeq();
		//insert 처리
		dto.setUserNo(no);
		//암호화
		dto.setUserPwd(pe.encode(dto.getUserPwd()));
		log.info(dto.toString());
		int result = dao.insertMember(dto);
		
		
		//////////////////////
		
		//파일 업로드(우리 서버에)
		MultipartFile f = dto.getF();
		
		if(!f.isEmpty()) {
			//원래 이름	-> db에 저장
			//변경된 이름 -> db에 저장
			//서비스 레이어에서 작업하도록
			String changeName = System.currentTimeMillis()+"_"+f.getOriginalFilename();
			dto.setChangeName(changeName);
			//사이즈, 타입
			System.out.println("===============");
			System.out.println(f.getOriginalFilename());
			System.out.println(f.getSize());
			System.out.println(f.getContentType());
			System.out.println("===============");
			
			//파일을 톰캣에 저장
			String path = req.getServletContext().getRealPath("/resources/upload/profile/");
			//파일을 서버에 저장
			//getREalPath == /spring999prjFinal/src/main/webapp
//			File file = new File("D:/uploadForSpring/999prj/profile/"+ changeName);
			File file = new File(path+ changeName);
			f.transferTo(file);
			
			//db에 insert
			dao.uploadProfile(dto);
		}
		
		return result;
	}

	@Override
	public MemberDto login(MemberDto dto) throws Exception {
		//DB에서 회원 정보 조회
		MemberDto dbUser = dao.getMember(dto);
		
		//비번 일치 체크
		if(pe.matches(dto.getUserPwd(), dbUser.getUserPwd())) {
			//일치함-> 멤버 리턴
			return dbUser;
		}else {
			//불일치-> null 리턴
			return null;
		}
	}

	@Override
	public MemberDto editMember(MemberDto dto) throws Exception {
		//비밀번호 한번 더 확인..근데 여기선 패스
		//비번을 입력했을 때만 수정 가능!!
		if(dto.getUserPwd().length()>0) {
			dto.setUserPwd(pe.encode(dto.getUserPwd()));
		}
		int result = dao.updateMember(dto);
		MemberDto m = null;
		if(result > 0) {
			m = dao.getMember(dto);
		}
		return m;
	}

}


MemberDao

public interface MemberDao {
	
	int getMemberSeq() throws Exception;

	int insertMember(MemberDto dto) throws Exception;

	void uploadProfile(MemberDto dto) throws Exception;

	MemberDto getMember(MemberDto dto) throws Exception;

	int updateMember(MemberDto dto) throws Exception;
}


MemberDaoImpl

@Repository
public class MemberDaoImpl implements MemberDao{

	@Autowired
	private SqlSession sqlSession;
	
	
	@Override
	public int getMemberSeq() throws Exception {
		return sqlSession.selectOne("member.getSeq");
	}

	@Override
	public int insertMember(MemberDto dto) throws Exception{
		return sqlSession.insert("member.insertMember", dto);
	}

	@Override
	public void uploadProfile(MemberDto dto) throws Exception {
		sqlSession.insert("member.insertProfile", dto);
	}

	@Override
	public MemberDto getMember(MemberDto dto) throws Exception {
		
		return sqlSession.selectOne("member.getMember", dto);
	}

	@Override
	public int updateMember(MemberDto dto) throws Exception{
		return sqlSession.update("member.updateMember", dto);
	}
	
}


member-mapper.xml

<mapper namespace="member">

	<select id="getSeq" resultType="int">
		SELECT MEMBER_SEQ.NEXTVAL FROM DUAL
	</select>
	
	<insert id="insertMember" parameterType="memberDto">
		INSERT INTO MEMBER
		(
			 USER_NO 
		    ,USER_ID
		    ,USER_PWD 
		    ,USER_NICK 
		    ,USER_AGE   
		    ,USER_GENDER 
		)
		VALUES
		(
			#{userNo}
			,#{userId}
			,#{userPwd}
			,#{userNick}
			,#{userAge}
			,#{userGender}
		)
		
	</insert>
 
 	<insert id="insertProfile" parameterType="memberDto">
 		INSERT INTO MEMBER_PROFILE
 		(
 		    FILE_NO
		    ,USER_NO
		    ,CHANGE_NAME
 		)
 		VALUES
 		(
 			 MEMBER_PROFILE_SEQ.NEXTVAL
 			 ,#{userNo}
 			 ,#{changeName}
 		)
 	
 	</insert>
 	
 	<select id="getMember" parameterType="memberDto" resultType="memberDto">
 		SELECT * 
 		FROM MEMBER M
 		JOIN MEMBER_PROFILE P ON (M.USER_NO = P.USER_NO)
 		WHERE USER_ID = #{userId}
 	</select>
 	
 	<update id="updateMember" parameterType="memberDto">
 		UPDATE MEMBER
 		SET 
 			USER_NO = #{userNo}
			<if test="userPwd != null and userPwd != ''">
			    ,USER_PWD = #{userPwd}
			</if>
			<if test="userNick != null and userNick != ''">
			    ,USER_NICK = #{userNick}
			</if>
			<if test="userAge != null and userAge != ''">
			    ,USER_AGE = #{userAge}
			</if>
			<if test="userGender != null and userGender != ''">
			    ,USER_GENDER = #{userGender}
			</if>
		
		WHERE USER_NO = #{userNo}
 	</update>

</mapper>


MemberDto

@Data
public class MemberDto {

	private long userNo;
	private String userId;
	private String userPwd;
	private String userNick;
	private int userAge;
	private String userGender;
	private MultipartFile f;
	private String changeName;
}



resources/upload/profile




mypage.jsp

<body>
	<%@ include file="/WEB-INF/views/common/header.jsp" %>
	<div id="div-main">
		<h1>마이페이지</h1>
		
		<form action = "" method = "post" enctype="multipart/form-data">
	        <input type = hidden name = "userNo" value="${loginUser.userNo}"/><br>
	        아이디 : <input type = "text" name = "userId" value="${loginUser.userId}" readonly="readonly"/><br>
	        비밀번호 : <input type = "password" name = "userPwd"/><br>
	        닉네임 : <input type = "text" name = "userNick" value="${loginUser.userNick}"/><br>
	        나이 : <input type = "number" min="0" name = "userAge" value="${loginUser.userAge}"/><br>
	        성별 : 
	        <select name="userGender">
		        <c:if test="${loginUser.userGender eq 'm'}">
		        	<option value="m" selected="selected">남자</option>
		        	<option value="f">여자</option>
		        </c:if>
		        <c:if test="${loginUser.userGender ne 'm'}">
		        	<option value="m">남자</option>
		        	<option value="f" selected="selected">여자</option>
		        </c:if>
	        </select><br>
	        사진 : <input type = "file" name = "f" multiple="multiple" accept=".jpg, .png"/><br>
	        <img id="profileImg"><br><hr>
	        <div id="div-preview">
	        
	        </div>
	        <input type = "submit" value ="수정하기"/>
	    </form>
	</div>
</body>


login.jsp

<body>

	<%@ include file="/WEB-INF/views/common/header.jsp" %>
	
	<div id="div-main">
		<h1>로그인 페이지</h1>
	
		<form action = "" method = "post">
	        아이디 : <input type = "text" name = "userId"/><br>
	        비밀번호 : <input type = "password" name = "userPwd"/><br>
	        <input type = "submit" value ="로그인"/>
	    </form>
		
		<a href="join">회원가입</a>
	</div>
</body>



DB

MEMBER

delete member;
drop table member;
CREATE TABLE MEMBER(
    USER_NO NUMBER PRIMARY KEY
    ,USER_ID VARCHAR2(100)
    ,USER_PWD VARCHAR2(100)
    ,USER_NICK VARCHAR2(100)
    ,USER_AGE   NUMBER
    ,USER_GENDER    CHAR(1)
    --,USER_PROFILE   VARCHAR2(500)
);

DROP SEQUENCE MEMBER_SEQ;
CREATE SEQUENCE MEMBER_SEQ NOCACHE NOCYCLE;

COMMIT;
SELECT * FROM MEMBER;

SELECT MEMBER_SEQ.NEXTVAL FROM DUAL;


MEMBER_PROFILE

DROP TABLE MEMBER_PROFILE;
CREATE TABLE MEMBER_PROFILE(
    FILE_NO NUMBER PRIMARY KEY
    ,USER_NO NUMBER
    ,CHANGE_NAME VARCHAR2(512)
    ,CONSTRAINT MEMBER_PROFILE_FK FOREIGN KEY(USER_NO) REFERENCES MEMBER(USER_NO) ON DELETE CASCADE
);

DROP SEQUENCE MEMBER_PROFILE_SEQ;
CREATE SEQUENCE MEMBER_PROFILE_SEQ NOCACHE NOCYCLE;

SELECT * FROM MEMBER_PROFILE;



에러 페이지

errorPage.jsp

<body>

	<%@ include file="/WEB-INF/views/common/header.jsp" %>

	<h1>에러페이지~~</h1>
	<h2 id="msg">${msg}</h2>
	
	<script type="text/javascript">
		alert(document.getElementById('msg').innerText);	//메세지 띄우기
		wiwdow.location.href = "${root}";	//홈화면으로 보내기
	</script>
</body>

0개의 댓글