2021/05/25(화)
Spring 공유캘린더 프로젝트 기본설정 참고
https://cordingdoah.tistory.com/111
로그인을 구현해보도록 하겠다
src/main/java 밑에 패키지 생성
- org.alpreah.domain
- org.alpreah.persistence
- org.zerock.controller
src/main/resources 밑에 폴더 생성
- mappers 폴더 밑에
- memberMapper.xml 생성
views 밑에 jsp파일 생성
- login.jsp (로그인 화면)
- pw.jsp (비밀번호 찾기 후 찾은 비밀번호 출력화면)
- pwFind.jsp (비밀번호 찾기 화면)
- register.jsp (회원가입 화면)
- index.jsp (로그인 후 메인 화면)
연동하기 앞서 member 테이블을 mariaDB에 생성
member테이블의 스키마
org.alpreah.domain 패키지 밑에 member.java 파일 생성
<member.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;
}
}
회원의 정보를 담을 변수와 메소드 생성
org.alpreah.persistence 패키지 밑에 member_dao.java 생성
<member_dao.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;
}
}
}
NameSpace를 통해 memeberMapper.xml을 연결하여 sql문을 사용 각 메소드의 값을 전달 받음
mappers 폴더 밑에 memberMapper.xml
<memberMapper.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>
각각 로그인, 회원가입, 비번찾기, 중복확인 같은 sql문으로 db를 조회해야할 때 memeberMapper.xml 사용
<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>
<typeAliases>
<typeAlias alias="Member" type="org.alpreah.domain.member" />
</typeAliases>
</configuration>
org.zerock.controller 패키지 밑에 LoginController.java 생성
<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;
}
}
requestMappting을 통해서 처음 실행하면 login.jsp 실행
views 폴더 밑에 login.jsp 파일 생성
<login.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">Login 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">Login</h3>
<div class="form-group">
<label for="username" 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="password" class="text-info">Password:</label><br>
<input type="password" name="m_pw" id="m_pw" class="form-control" placeholder="Password">
</div>
<br>
<div class="form-group" style="display:flex;">
<button id="login_process" type="button" class="btn btn-info btn-md" style="margin: 0 auto;">Submit</button>
</div>
<div id="register-link" class="text-right">
<a href="/register" class="text-info">Register here</a>
</div>
<div class="text-right">
<a href="/pwFind" class="text-info">Password Serch</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() {
$("#login_process").click(function() {
var json = {
m_id : $("#m_id").val(),
m_pw : $("#m_pw").val()
};
for ( var str in json) {
if (json[str].length == 0) {
alert($("#" + str).attr("placeholder") + "를 입력해주세요.");
$("#" + str).focus();
return;
}
}
$.ajax({
type : "post",
url : "Login",
data : json,
success : function(data) {
switch (Number(data)) {
case 0:
alert("아이디 또는 비밀번호가 일치하지 않습니다.");
break;
case 1:
window.location.href = "/index?m_id=" + $("#m_id").val();
default:
break;
}
},
error : function(error) {
alert("오류 발생" + error);
}
});
});
});
</script>
</body>
</html>
id, password 입력창을 띄우고 submit 버튼을 생성
회원가입과 비번찾기는 a 태그를 주어 하이퍼링크를 걸어줌
submit 버튼을 클릭시 id 값인 login_process를 이용하여 jQuery문으로 클릭을 받아 jason과 ajax를 사용하여
id, 비밀번호 일치 여부를 판단 후 일치하면 index.jsp로 아이디값을 넘겨서 화면 전환
--> 결과화면
'코딩 연습장 > Spring' 카테고리의 다른 글
Spring 공유 캘린더 프로젝트 - 6 (캘린더 화면) (0) | 2021.06.25 |
---|---|
Spring 공유 캘린더 프로젝트 - 5 (메인 화면) (0) | 2021.06.24 |
Spring 공유 캘린더 프로젝트 - 4 (비밀 번호 찾기) (0) | 2021.06.24 |
Spring 공유 캘린더 프로젝트 - 3 (회원 가입) (0) | 2021.06.24 |
Spring 공유 캘린더 프로젝트 - 1 (기본 설정) (0) | 2021.06.23 |