<form action="/join.do" method="post" id="form">
<div class="row">
<div class="col-sm">
<div class="form-floating mb-2">
<input type="text" id="id" class="form-control" onkeyup="ajaxIDCheck(this);" />
<label for="id" id="lbl_check" class="form-label">아이디</label>
</div>
...
</form>
form문을 추가하고
아이디, 암호, 이름, 나이에 name을 설정해준다. name="id", name="pw" ...
<script>
// 공통변수 모든 함수에서 사용가능함.
var idcheck = 0; // 1이면 사용가능 0은 사용불가
function joinAction() {
const id = document.getElementById("id");
const pw = document.getElementById("pw");
const pw1 = document.getElementById("pw1");
const name = document.getElementById("name");
const age = document.getElementById("age");
if(id.value.length <= 0){
alert('아이디를 입력하세요.');
id.focus();
return false; // 함수 종료, 전송하지 않음
}
if( pw.value !== pw1.value){
alert('암호가 일치하지 않습니다.');
pw1.focus();
return false;
}
if(idcheck === 0){
alert('사용가능한 아이디를 입력하세요.');
id.focus();
return false;
}
document.getElementById("form").submit();
}
그리고 script에 함수들을 입력한다.
아이디를 입력하지 않고 회원가입 버튼을 눌렀을 때.
암호와 암호확인이 서로 같지 않을 때.
사용이 불가능한 아이디를 입력하여 회원가입을 할 때.
각각 설정한 알림창이 뜬다.
public class Member {
private String id;
private String password;
private String newpw;
private String name;
private int age;
private Date regdate ;
private String role; // 고객 customer, 판매자 seller
}
dto를 이렇게 설정하고
// 회원가입
@Insert({
" INSERT INTO member (id, password, name, age, role) ",
" VALUES( #{obj.id}, #{obj.password}, #{obj.name}, #{obj.age}, #{obj.role}) "
})
public int insertMemberOne(@Param("obj") Member obj);
Mapper를 생성한 후
@WebServlet(urlPatterns = {"/customer/join.do"})
public class CustomerJoinController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/customer/customer_join.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 암호 hash하기
String hashPw = Hash.hashPW(request.getParameter("id"), request.getParameter("pw"));
// 전송되는 4개 값 받기
Member obj = new Member();
obj.setId( request.getParameter("id") );
obj.setPassword( hashPw );
obj.setName( request.getParameter("name") );
obj.setAge( Integer.parseInt(request.getParameter("age")) );
obj.setRole("customer");
// mapper를 이용해서 추가
int ret = MybatisContext.getSqlSession().getMapper(MemberMapper.class).insertMemberOne(obj);
if(ret == 1) {
// 127.0.0.1:8080/web02/customer/home.do
response.sendRedirect("home.do");
}
else {
response.sendRedirect(request.getContextPath() + "/customer/join.do");
}
}
}
CustomerJoinController.java를 생성하여 위처럼 작성한다.
이렇게 회원가입을 해보자.
home.do로 넘어갔으니 성공이다.
DB에도 잘 들어갔다.
mapper와 controller에 role을 없애고 시도해보자.
// 회원가입
@Insert({
" INSERT INTO member (id, password, name, age) ",
" VALUES( #{obj.id}, #{obj.password}, #{obj.name}, #{obj.age}) "
})
public int insertMemberOne(@Param("obj") Member obj);
mapper
Member obj = new Member();
obj.setId( request.getParameter("id") );
obj.setPassword( hashPw );
obj.setName( request.getParameter("name") );
obj.setAge( Integer.parseInt(request.getParameter("age")) );
//obj.setRole("customer");
controller
성공이라고 한다.
ROLE에 customer가 정상적으로 들어갔다.
ALTER로 ROLE의 기본값을 customer로 지정했기 때문에 추가할 때 ROLE을 따로 지정하지 않으면
customer로 등록이 된다.
@WebServlet(urlPatterns = {"/customer/home.do"})
public class CustomerHomeController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/customer/customer_home.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
CustomerHomeController.java를 생성하고
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>고객용 홈</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<a href="home.do">홈으로</a>
<a href="login.do">로그인</a>
<a href="join.do">회원가입</a>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script>
</script>
</body>
customer_home.jsp를 생성한다.
일단은 생성.
회원가입을 하면
홈으로 오게 된다.
<body>
<div class="container">
<a href="home.do">홈으로</a>
<a href="login.do">로그인</a>
<a href="#" onclick="logoutAction()">로그아웃</a>
<form action="logout.do" method="post">
<input type="submit" value="로그아웃" />
</form>
<a href="join.do">회원가입</a>
<hr />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script>
function logoutAction() {
var form = document.createElement("form");
form.setAttribute("action", "logout.do");
form.setAttribute("method", "post");
form.style.display="none";
document.body.appendChild(form);
form.submit();
}
</script>
</body>
이렇게 추가하면
로그아웃 창까지 생성된다.
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>고객용 로그인</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div style="width:600px; margin:0 auto; padding: 50px; border:1px solid #efefef;">
<h3>로그인</h3>
<form action="login.do"></form> <!-- /web02/customer/여기만 바뀜 -->
<form action="/login.do"></form> <!-- /login.do -->
<form action="${pageContext.request.contextPath}/customer/login.do" method="post" id="form">
<div class="row">
<div class="col-sm">
<div class="form-floating mb-2">
<input type="text" name="id" id="id" class="form-control" onkeyup="ajaxIDCheck(this);" />
<label for="id" class="form-label">아이디</label>
</div>
<div class="form-floating mb-2">
<input type="password" name="pw" id="pw" class="form-control" />
<label for="pw" class="form-label">암호</label>
</div>
<div>
<input type="button" value="로그인" class="btn btn-primary" onclick="loginAction()"/>
<a href="join.do" class="btn btn-primary">회원가입</a>
<중략>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script>
if(Number('${param.code}'==0)) {
alert('아이디 또는 암호가 틀렸습니다.');
}
function loginAction() {
const id = document.getElementById("id");
const pw = document.getElementById("pw");
if(id.value.length <= 0){
alert('아이디를 입력하세요.');
id.focus();
return false; // 함수 종료, 전송하지 않음
}
if(pw.value.length<= 0){
alert('비밀번호를 입력하세요.');
pw.focus();
return false;
}
document.getElementById("form").submit();
}
</script>
customer_login.jsp를 생성하였다.
@WebServlet(urlPatterns = {"/customer/login.do"})
public class CustomerLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/customer/customer_login.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 암호 hash하기
String hashPw = Hash.hashPW(request.getParameter("id"), request.getParameter("pw"));
// 아이디, 암호 받기
Member obj = new Member();
obj.setId( request.getParameter("id") );
obj.setPassword( hashPw );
// mapper를 이용해서 추가
Member ret = MybatisContext.getSqlSession().getMapper(MemberMapper.class).selectMemberLogin(obj);
if(ret != null) {
HttpSession httpSession = request.getSession();
// 세션에 기록하기. 기본시간 30분
httpSession.setAttribute("id", ret.getId());
httpSession.setAttribute("role", ret.getRole());
httpSession.setAttribute("name", ret.getName());
response.sendRedirect("home.do");
return; // 메소드
}
response.sendRedirect(request.getContextPath() + "/customer/login.do");
}
}
CustomerLoginController.java를 생성하였다.
아이디를 입력하지 않았을 때.
비밀번호를 입력하지 않았을 때.
아이디와 비밀번호가 일치하지 않으면 알림창과 함께 다시 login.do로 넘어온다.
일치하는 아이디와 비밀번호로 로그인하면 home.do로 이동한다.
@WebServlet(urlPatterns = {"/api/member/login.json"})
public class RestMemberLoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
private Gson gson = new Gson();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hashPw = Hash.hashPW( request.getParameter("id"),request.getParameter("pw"));
Member obj = new Member();
obj.setId( request.getParameter("id") );
obj.setPassword( hashPw );
System.out.println(obj.toString());
Member ret = MybatisContext.getSqlSession().getMapper(MemberMapper.class).selectMemberLogin(obj);
response.setContentType("application/json");
Map<String, Object> map = new HashMap<>();
map.put("ret", 0); // 실패시
if(ret != null) {
// react.js, vue.js등의 프런트엔드 프레임워크 개발시 토큰을 발행시킴
HttpSession httpSession = request.getSession();
httpSession.setAttribute("id", ret.getId());
httpSession.setAttribute("role", ret.getRole());
httpSession.setAttribute("name", ret.getName());
map.put("ret", 1); //성공시
}
String jsonString = gson.toJson(map);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
}
}
RestMemberLoginController.java를 생성한다.
<생략>
<hr />
<div style="width:600px; margin:0 auto; padding: 50px; border:1px solid #efefef;">
<h3>로그인(ajax)</h3>
<div class="row">
<div class="col-sm">
<div class="form-floating mb-2">
<input type="text" id="id1" class="form-control" />
<label for="id1" class="form-label">아이디</label>
</div>
<div class="form-floating mb-2">
<input type="password" id="pw1" class="form-control" />
<label for="pw1" class="form-label">암호</label>
</div>
<div>
<input type="button" value="로그인1" class="btn btn-primary"
onclick="loginAction1()"/>
<a href="join.do" class="btn btn-primary">회원가입</a>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script>
async function loginAction1(){
const id = document.getElementById("id1");
const pw = document.getElementById("pw1");
const url = '${pageContext.request.contextPath}/api/member/login.json';
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
const body = { id : id.value, pw : pw.value };
const { data } = await axios.post(url, body, {headers});
console.log(data);
if(data.ret === 1) {
alert('로그인 되었습니다.');
window.location.href='home.do';
}
else{
alert('아이디 또는 암호가 틀립니다.');
}
}
customer_login.jsp 에서 로그인칸을 한 칸 더 만들고 아래 script를 추가한다.
로그인칸이 추가된 화면
아이디 또는 암호가 틀렸을 때
로그인 성공한 화면.
@WebServlet(urlPatterns = {"/customer/logout.do"})
public class CustomerLogoutController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession httpSession = request.getSession();
httpSession.invalidate();
response.sendRedirect("home.do");
}
}
CustomerLogoutController.java를 생성한다.
<body>
<div class="container">
<a href="home.do">홈으로</a>
<c:if test="${sessionScope.id eq null}">
<a href="login.do">로그인</a>
<a href="join.do">회원가입</a>
</c:if>
<c:if test="${sessionScope.id ne null}">
<label>${sessionScope.name}님 로그인</label>
<a href="#" onclick="logoutAction()">로그아웃</a>
</c:if>
<hr />
</div>
customer_home.jsp의 body를 위처럼 수정한다.
가입되어있는 아이디와 암호로 로그인을 하면
해당하는 아이디의 name님 로그인 이라고 뜬다.
홈으로를 누르면 변함이 없다.
로그아웃을 눌렀다
이름이 사라지고 로그인 창이 새로 생겼다.
// 판매자 회원가입
@Insert({
" INSERT INTO member (id, password, name, age, role) ",
" VALUES( #{obj.id}, #{obj.password}, #{obj.name}, #{obj.age}, #{obj.role}) "
})
public int insertSellerMemberOne(@Param("obj") Member obj);
판매자 회원가입용 mapper를 생성하였다. customer와는 다르게 role을 추가하였다.
기본값이 customer이기 때문에 seller로 등록하기 위해 role을 추가하였다.
@WebServlet(urlPatterns = {"/api/seller/join.json"})
public class RestSellerJoinController extends HttpServlet {
private static final long serialVersionUID = 1L;
private Gson gson = new Gson();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String hashPw = Hash.hashPW( request.getParameter("id"),request.getParameter("pw"));
Member obj = new Member();
obj.setId( request.getParameter("id") );
obj.setPassword( hashPw );
obj.setName(request.getParameter("name"));
obj.setAge(Integer.parseInt(request.getParameter("age")));
obj.setRole("seller");
System.out.println(obj.toString());
int ret = MybatisContext.getSqlSession().getMapper(MemberMapper.class).insertSellerMemberOne(obj);
response.setContentType("application/json");
Map<String, Object> map = new HashMap<>();
map.put("ret", 0); // map =>{"result" : 0}
if(ret != 0) {
map.put("ret", 1); //map =>{"result" : 1}
}
// 오브젝트 타입 json으로 변경 (gson라이브러리)
String jsonString = gson.toJson(map);
PrintWriter out = response.getWriter();
out.print(jsonString);
out.flush();
}
}
RestSellerJoinController.java를 생성하여 위 코드를 추가한다.
결과가 1이 나온다면 제대로 들어갔다는 뜻이다.
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>판매자용 회원가입</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<div style="width:600px; margin:0 auto; padding: 50px; border:1px solid #efefef;">
<h3>판매자용 회원가입</h3>
<div class="row">
<div class="col-sm">
<div class="form-floating mb-2">
<input type="text" name="id" id="id" class="form-control" onkeyup="ajaxIDCheck(this);" />
<label for="id" id="lbl_check" class="form-label">아이디</label>
</div>
<div class="form-floating mb-2">
<input type="password" name="pw" id="pw" class="form-control" />
<label for="pw" class="form-label">암호</label>
</div>
<div class="form-floating mb-2">
<input type="password" id="pw1" class="form-control"/>
<label for="pw1" class="form-label">암호 확인</label>
</div>
<div class="form-floating mb-2">
<input type="text" name="name" id="name" class="form-control" />
<label for="name" class="form-label">이름</label>
</div>
<div class="form-floating mb-2">
<input type="number" name="age" id="age" class="form-control" />
<label for="age" class="form-label">나이</label>
</div>
<div>
<input type="button" value="회원가입" class="btn btn-primary" onclick="joinAction()"/>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.5/axios.min.js"></script>
<script>
// 공통변수 모든 함수에서 사용가능함.
var idcheck = 0; // 1이면 사용가능 0은 사용불가
async function ajaxIDCheck(e){
console.log(e.value);
if(e.value.length>0) {
// rest api 호출
const url = '${pageContext.request.contextPath}/api/member/idcheck.json?id=' + e.value;
const headers={"Content-Type":"application/json"};
const {data} = await axios.get(url, {headers});
// 결과값 받기
console.log(data);
if(data.ret === 1) {
// 사용불가
idcheck = 0;
document.getElementById("lbl_check").innerText = '사용불가';
}
else if(data.ret === 0) {
// 사용가능
idcheck = 1;
document.getElementById("lbl_check").innerText = '사용가능';
}
}
else{
idcheck = 0;
document.getElementById("lbl_check").innerText = '아이디';
}
}
async function joinAction() {
const id = document.getElementById("id");
const pw = document.getElementById("pw");
const name = document.getElementById("name");
const age = document.getElementById("age");
const url = '${pageContext.request.contextPath}/api/seller/join.json';
const headers = { "Content-Type": "application/x-www-form-urlencoded" };
const body = { id : id.value, pw : pw.value, name : name.value, age : age.value };
const { data } = await axios.post(url, body, {headers});
console.log(data);
if(id.value.length <= 0){
alert('아이디를 입력하세요.');
id.focus();
return false; // 함수 종료, 전송하지 않음
}
if( pw.value !== pw1.value){
alert('암호가 일치하지 않습니다.');
pw1.focus();
return false;
}
if(idcheck === 0){
alert('사용가능한 아이디를 입력하세요.');
id.focus();
return false;
}
if( name.value.length <=0 ){
alert('이름을 입력하세요.');
name.focus();
return false;
}
if(age.value.length <= 0){
alert('나이를 입력하세요.');
age.focus();
return false;
}
if(data.ret === 1) {
alert('가입 완료');
window.location.href='home.do';
}
else{
alert('가입 실패');
}
}
</script>
</body>
seller_join.jsp를 생성하였다.
중복된 아이디이므로 사용불가.
정상적으로 회원가입이 된다.
seller/home.do를 만들지 않았으니 404에러가 뜬다.
정상적으로 seller7이 들어갔다.
+
암호가 일치하지 않으면 일치하지 않는다는 알림이 뜬다.