코딩 연습장/Spring

Spring 공유 캘린더 프로젝트 - 3 (회원 가입)

Do아 2021. 6. 24. 11:33
728x90

2021/05/25(화)

 

 

 

 

 

 

Spring 공유 캘린더 프로젝트 로그인 알고리즘 참고

https://cordingdoah.tistory.com/112

 

Spring 공유 캘린더 프로젝트 - 2 (로그인)

2021/05/25(화) Spring 공유캘린더 프로젝트 기본설정 참고 https://cordingdoah.tistory.com/111 Spring 공유 캘린더 프로젝트 - 1 (기본 설정) 2021/05/25(화) Spring을 사용한 캘린더를 공유할 수 있는 프로젝..

cordingdoah.tistory.com

 

 

 

 

 

회원가입 화면과 db에 등록될 수 있도록 처리를 해보려고 한다

기존 로그인에서 했던 것과 비슷하게 하면 되는데 좀 더 자세히 설명을 해보겠다!

 

 

 

 

<LoginController.java>

package org.zerock.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import org.alpreah.domain.member;
import org.alpreah.persistence.member_dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.AbstractMappingJacksonResponseBodyAdvice;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class LoginController {

	@Autowired
	private member_dao m_dao;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String login() {
		return "login";
	}

	@ResponseBody
	@RequestMapping(value = "Login", method = RequestMethod.POST)
	public int login(member m, HttpSession session) {
		return m_dao.Login(m, session);
	}

	@RequestMapping("/pwFind")
	public String pwFind() {
		return "pwFind";
	}

	@ResponseBody
	@RequestMapping(value = "PwFind", method = RequestMethod.POST)
	public int pwFind(member m, HttpSession session) {
		return m_dao.pwFind(m, session);
	}

	@RequestMapping("/pw")
	public String pw() {
		return "pw";
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "register";
	}

	@ResponseBody
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public int register(member m) {
		return m_dao.Register(m);
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpSession session) {
		session.removeAttribute("m");
		return "redirect:/";
	}

	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public String show() {
		return "show";
	}
	
	@ControllerAdvice
	public class JsonpAdviceController extends AbstractMappingJacksonResponseBodyAdvice {
		public JsonpAdviceController() {
			super();
		}

		@Override
		protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
				MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {
			// TODO Auto-generated method stub

		}
	}

	@Bean
	public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
		MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		jsonConverter.setObjectMapper(objectMapper);
		return jsonConverter;
	}

}

 

 

위의 컨트롤러에서 회원가입의 관련된 부분은 아래부분

	/* 로그인 화면 --> 회원가입 버튼 클릭 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register() {
		return "register";
	}

	/* 회원가입 화면 --> 확인 버튼 */
	@ResponseBody
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public int register(member m) {
		return m_dao.Register(m);
	}

첫번째 메소드는 로그인창에서 회원가입 클릭 했을 때 실행

두번째 메소드는 회원가입창에서 확인버튼을 클릭했을 때 실행

 

 


 

 

<member.java>

- 회원 정보 저장및 조회 java

package org.alpreah.domain;

import lombok.Data;

@Data
public class member {
	private String m_name;
	private String m_id;
	private String m_pw;
	private String m_pwc;
	private String m_hint;
	private String m_anw;
	
	public String getM_name() {
		return m_name;
	}
	public void setM_name(String m_name) {
		this.m_name = m_name;
	}
	public String getM_id() {
		return m_id;
	}
	public void setM_id(String m_id) {
		this.m_id = m_id;
	}
	public String getM_pw() {
		return m_pw;
	}
	public void setM_pw(String m_pw) {
		this.m_pw = m_pw;
	}	
	public String getM_pwc() {
		return m_pwc;
	}
	public void setM_pwc(String m_pwc) {
		this.m_pwc = m_pwc;
	}
	public String getM_hint() {
		return m_hint;
	}
	public void setM_hint(String m_hint) {
		this.m_hint = m_hint;
	}
	public String getM_anw() {
		return m_anw;
	}
	public void setM_anw(String m_anw) {
		this.m_anw = m_anw;
	}
}

 

 


 

 

<member_dao.java>

- sql문 사용 후 저장을 위한 java

package org.alpreah.persistence;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import org.alpreah.domain.member;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@SuppressWarnings("unused")
@Repository
public class member_dao {
	@Autowired
	private SqlSession session;
	private static final String NameSpace = "memberMapper.";
	
	public int Id_Check(member m) {
		try {
			return session.selectOne(NameSpace + "Id_Check", m);
		}
		catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public int Register(member m) {
		int Id_Check_Result = Id_Check(m);
		if(Id_Check_Result != 0) return Id_Check_Result;
		
		try {
			session.insert(NameSpace + "Register", m);
			return 0;
		}
		catch (Exception e) {
			e.printStackTrace();
			return -2;
		}
	}
	
	public int Login(member m, HttpSession Hsession) {
		int Id_Search_Result = -1;
		try {
			Id_Search_Result = session.selectOne(NameSpace + "Login", m);
		}
		catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
		
		if(Id_Search_Result != 1) return Id_Search_Result;
		
		try {
			member m_info = session.selectOne(NameSpace + "Login_Info", m);
			Hsession.setAttribute("m", m_info);
			return 1;
		}
		catch (Exception e) {
			e.printStackTrace();
			return -2;
		}
	}	
	public int pwFind(member m, HttpSession Hsession) {
		int Id_Search_Result = -1;
		try {
			Id_Search_Result = session.selectOne(NameSpace + "Pw_find", m);
		}
		catch (Exception e) {
			 e.printStackTrace(); 
		
			return -1;
		}
		
		if(Id_Search_Result != 1) return Id_Search_Result;
		
		try {
			member m_info = session.selectOne(NameSpace + "Pw", m);
			Hsession.setAttribute("m", m_info);
			return 1;
		}
		catch (Exception e) {
			e.printStackTrace(); 
			return -2;
		}
	}
}

 

 

위에 부분에서 회원가입 관련 부분

	
	public int Register(member m) {
		int Id_Check_Result = Id_Check(m);
		if(Id_Check_Result != 0) return Id_Check_Result;
		
		try {
			session.insert(NameSpace + "Register", m);
			return 0;
		}
		catch (Exception e) {
			e.printStackTrace();
			return -2;
		}
	}

 


 

 

<memberMapper.xml>

- 실제 sql사용하는 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="memberMapper">

	<select id="Id_Check" resultType="int">
		select count(*) from member m
		where m.m_id = #{m_id}
	</select>

	<insert id='Register'>
		INSERT INTO member (m_name, m_id, m_pw, m_pwc,
		m_hint, m_anw)
		VALUES (#{m_name}, #{m_id}, #{m_pw}, #{m_pwc},
		#{m_hint}, #{m_anw})
	</insert>

	<select id="Login" resultType="int">
		select count(*) from member m
		where m.m_id = #{m_id} and m.m_pw = #{m_pw}
	</select>

	<select id="Login_Info" resultType="Member">
		select * from member m
		where
		m.m_id = #{m_id} and m.m_pw = #{m_pw}
	</select>

	<select id="Pw_find" resultType="int">
		select count(*) from member m
		where m.m_id = #{m_id} and m.m_hint = #{m_hint} and m.m_anw = #{m_anw}
	</select>

	<select id="Pw" resultType="Member">
		select * from member m
		where m.m_id =
		#{m_id} and m.m_hint = #{m_hint} and m.m_anw = #{m_anw}
	</select>
</mapper>

 

 

위의 코드에서 회원가입과 관련있는 코드

	<!-- ID 중복체크 -->
	<select id="Id_Check" resultType="int">
		select count(*) from member m
		where m.m_id = #{m_id}
	</select>

	<!-- 회원가입 -->
	<insert id='Register'>
		INSERT INTO member (m_name, m_id, m_pw, m_pwc,
		m_hint, m_anw)
		VALUES (#{m_name}, #{m_id}, #{m_pw}, #{m_pwc},
		#{m_hint}, #{m_anw})
	</insert>

 

 


 

 

<register.jsp>

- 회원가입 화면

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>

<meta charset="UTF-8">
<title>회원가입 데모</title>
</head>
<body>
	<div id="login">
		<h3 class="text-center text-white pt-5">Register form</h3>
		<div class="container">
			<div id="login-row"
				class="row justify-content-center align-items-center">
				<div id="login-column" class="col-md-6">
					<div id="login-box" class="col-md-12">
						<form id="login-form" class="form" action="" method="post">
							<h3 class="text-center text-info">Register</h3>
							<div class="form-group">
								<label for="m_name" class="text-info">Name:</label><br> <input
									type="text" name="m_name" id="m_name" class="form-control" placeholder="Name">
							</div>
							<div class="form-group">
								<label for="m_id" class="text-info">Id:</label><br> <input
									type="text" name="m_id" id="m_id" class="form-control" placeholder="ID">
							</div>
							<div class="form-group">
								<label for="m_pw" class="text-info">Password:</label><br> <input
									type="password" name="m_pw" id="m_pw" class="form-control" placeholder="Password">
							</div>
							<div class="form-group">
								<label for="m_pwc" class="text-info">Password Check:</label><br>
								<input type="password" name="m_pwc" id="m_pwc" class="form-control" placeholder="Password Check">
							</div>
							<div class="form-group">
								<label for="m_hint" class="text-info">Password Hint:</label><br>
								<select id="m_hint" name="m_hint" class="form-control">
									<option>Password Serch Hint</option>
									<option>What year were you born?</option>
									<option>Birth region</option>
									<option>My Treasure No. 1</option>
									<option>Graduated elementary school</option>
									<option>the place of one's family register</option>
								</select>
							</div>
							<div class="form-group">
								<label for="m_anw" class="text-info">Answer:</label><br> <input
									type="text" name="m_anw" id="m_anw" class="form-control" placeholder="Answer">
							</div>
							<br>
							<div class="form-group" style="display:flex;">
                				<button id="register_process" type="button" class="btn btn-info btn-md" style="margin: 0 auto;">Submit</button>
                			</div>
							<div id="login-link" class="text-right">
								 <a href="/" class="text-info">Login here</a>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</div>
	<script
		src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
	<script>
		$(document)
				.ready(
						function() {
							$("#register_process")
									.click(
											function() {
												var json = {
													m_name : $("#m_name").val(),
													m_id : $("#m_id").val(),
													m_pw : $("#m_pw").val(),
													m_pwc : $("#m_pwc").val(),
													m_hint : $("#m_hint").val(),
													m_anw : $("#m_anw").val()
												};

												for ( var str in json) {
													if (json[str].length == 0) {
														alert($("#" + str)
																.attr(
																		"placeholder")
																+ "를 입력해주세요.");
														$("#" + str).focus();
														return;
													}
												}

												$
														.ajax({
															type : "post",
															url : "register",
															data : json,
															success : function(
																	data) {
																switch (Number(data)) {
																case 0:
																	alert("정상적으로 회원가입 되었습니다.");
																	window.location.href = "/";
																	break;
																case 1:
																	alert("아이디가 중복 되었습니다.");
																	break;
																default:
																	alert("알수없는 오류가 발생 했습니다. [Error Code :"
																			+ Number(data)
																			+ "]");
																	break;
																}
															},
															error : function(
																	error) {
																alert("오류 발생"
																		+ error);
															}
														});
											});
						});
		$(function() {

			//비밀번호 확인
			$('#m_pwc').blur(function() {
				if ($('#m_pw').val() != $('#m_pwc').val()) {
					if ($('#m_pwc').val() != '') {
						alert("비밀번호가 일치하지 않습니다.");
						$('#m_pwc').val('');
						$('#m_pwc').focus();
					}
				}
			})
		});
	</script>
</body>

</html>


 

 

 

 

대략적으로 설명을하자면 로그인 화면에서 회원가입 버튼을 클릭하면 /register로 가게되는데 컨트롤러에서 인식을 하고 register.jsp 화면을 웹에 띄워주고 회원가입 화면에서 정보를 입력하고 확인을 클릭하면 ajax를 통해 url로 register를 받게되고 다시 컨트롤러로 돌아가 sql문을 실행 조건이 맞으면 가입성공

 

 

 

-->결과 화면

 

728x90