겉바속촉
[spring] 로그인 만들어주기 본문
지난번 포스팅에 이어서 해보도록 하쥬
2020/07/06 - [취업일기/SPRING] - [spring] 사이트 만들기
2020/07/07 - [취업일기/SPRING] - [spring] db에 저장해주고 수정, 삭제까지
다음과 같이 필요한 패키지와 파일들 만들어주세요:)
MemberSql.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"> </mapper>
SqlMapConfig.xml 에 추가해서 다음 전체 코드
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTDConfig 3.0//EN" "HTTP://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias type="info.data.InfoDto" alias="idto"/> <typeAlias type="member.data.MemberDto" alias="mdto"/> </typeAliases> <mappers> <mapper resource="mybatis/setting/InfoSql.xml"/> <mapper resource="mybatis/setting/MemberSql.xml"/> </mappers> </configuration>
menu.jsp에 다음 추가
<a href="${path }/member/insertform">회원가입</a> <a href="${path }/member/list">회원목록</a>
menu.jsp 전체 코드
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <a href="${path }/home">Home </a> <a href="${path }/info/insertform">입력폼</a> <a href="${path }/info/list">목록</a> <a href="${path }/member/insertform">회원가입</a> <a href="${path }/member/list">회원목록</a> </body> </html>
member2 테이블 생성
테이블에 값 하나 주입
MemberDto.java
package member.data; import java.sql.Timestamp; public class MemberDto { private String num; private String name; private String id; private String pass; private Timestamp gaipday; public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getPass() { return pass; } public void setPass(String pass) { this.pass = pass; } public Timestamp getGaipday() { return gaipday; } public void setGaipday(Timestamp gaipday) { this.gaipday = gaipday; } }
MemberDaoInter
package member.data; import java.util.List; public interface MemberDaoInter { public List<MemberDto> getAllDatas(); public void insertMember(MemberDto dto); }
MemberSql
<?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="selectAllDataOfMember" resultType="mdto"> select * from member2 order by num asc </select> <insert id="insertOfMember" parameterType="mdto"> insert into member2 values(seq_mem.nextval, #{name},#{id},#{pass},sysdate) </insert> </mapper>
MemberDao는
1. extends적어주고 _ SqlSessionDaoSupport
2. implements 적어주고 _ MmeberDaoInter
3. @Repository
package member.data; import java.util.List; import org.mybatis.spring.support.SqlSessionDaoSupport; import org.springframework.stereotype.Repository; @Repository public class MemberDao extends SqlSessionDaoSupport implements MemberDaoInter { @Override public List<MemberDto> getAllDatas() { // TODO Auto-generated method stub return getSqlSession().selectList("selectAllDataOfMember"); } @Override public void insertMember(MemberDto dto) { // TODO Auto-generated method stub getSqlSession().insert("insertOfMember", dto); } }
MemberController
1. @Controller
2. @Autowired
3. get인지 post인지 파악 후 @GetMapping, @PostMapping
package spring.mvc.board; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView; import member.data.MemberDaoInter; import member.data.MemberDto; @Controller public class MemberController { @Autowired MemberDaoInter dao; @GetMapping("/member/list") public ModelAndView list() { ModelAndView model=new ModelAndView(); List<MemberDto>list=dao.getAllDatas(); model.addObject("list", list); model.addObject("cnt", list.size()); model.setViewName("/member/memberList"); //타일즈형식 return model; } }
memberList
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <button type="button" class="btn btn-info" style="width: 100px; margin-left: 500px;" onclick="location.href=${path}/member/insertform">회원가입</button> <br><br> 명단나올곳 </body> </html>
실행시켜서 회원목록 클릭하면
테스트용으로 적어둔 명단나올 곳이 뜹니다
테스트용이 잘 뜨신다면
이제 list를 완성해보도록 하쥬:)
memberList
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <button type="button" class="btn btn-info" style="width: 100px; margin-left: 500px;" onclick="location.href=${path}/member/insertform">회원가입</button> <br><br> <div class="container"> <table class="table table-bordered"> <tr> <th>번호</th> <th>이름</th> <th>아이디</th> <th>비밀번호</th> <th>가입날짜</th> <th>편집</th> </tr> <c:forEach var="a" items="${list }" varStatus="i"> <tr> <td>${i.count}</td> <td>${a.name}</td> <td>${a.id}</td> <td>${a.pass}</td> <td><fmt:formatDate value="${a.gaipday }" pattern="yyyy-MM-dd HH:mm"/></td> <td><a href="updateform?num=${a.num }">수정</a>/ <a href="delete?num=${a.num }">삭제</a></td> </tr> </c:forEach> </table> </div> </body> </html>
이제 새로고침 눌러볼까요?
MemberController에 다음 추가
//회원가입 누르면 폼 열리기 @GetMapping("/member/insertform") public String memberform() { return "/member/memberForm"; }
memberForm
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <form action="${path }/member/insert" method="post"> <table class="table table-hover" style="width: 400px;"> <caption>[회원가입]</caption> <tr> <th>회원명</th> <td> <input type="text" size="10" name="name" autofocus="autofocus" required="required" class="form-cotrol"> </td> </tr> <tr> <th>아이디</th> <td> <input type="text" size="15" name="id" required="required" class="form-cotrol"> </td> </tr> <tr> <th>비밀번호</th> <td> <input type="password" size="15" name="pass" required="required" class="form-cotrol" > </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="회원가입" class="btn btn-info"> <input type="button" value="회원목록" class="btn btn-info" onclick="location.href='${path }/member/list'"> </td> </tr> </table> </form> </body> </html>
다시 실행시켜보면
회원목록을 누르면 list로 가는 지도 확인해주셔야됩니다!!
로그인 , 로그아웃
menu.jsp로 가서 로그인 부분 추가해주기
<a href="${path }/login/login">로그인</a>
menu.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <a href="${path }/home">Home </a> <a href="${path }/info/insertform">입력폼</a> <a href="${path }/info/list">목록</a> <a href="${path }/member/insertform">회원가입</a> <a href="${path }/member/list">회원목록</a> <a href="${path }/login/login">로그인</a> </body> </html>
loginController
package spring.mvc.board; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { @GetMapping("/login/login") public String loginform() { return "/login/loginForm"; } }
loginForm
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <div class="container"> <form action="loginproc" method="post"> <table class="table table-hover" style="width: 400px;"> <caption>세션로그인</caption> <tr> <th>아이디</th> <td> <input type="text" name="id" size="10" placeholder="아이디" required="required" class="form-control"> <input type="checkbox" name="idsave">아이디저장 </td> </tr> <tr> <th>비밀번호</th> <td> <input type="password" name="pass" size="10" placeholder="비밀번호" required="required"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="로그인"> <input type="button" value="회원가입" onclick="location.href='${path}/member/insertform'"> </td> </tr> </table> </form> </div> </body> </html>
MemberSql
<!-- 아이디 비번 일치하면 로그인 --> <select id="loginSuccess" parameterType="HashMap" resultType="int"> select count(*) from member2 where id=#{id} and pass=#{pass} </select>
<!-- 이름 얻는 것 id받아서 name 얻는 것 --> <select id="nameByMember" parameterType="String" resultType="String"> select name from member2 where id=#{id} </select>
MemberDaoInter
//아이디비번체크 public boolean isLogin(String id, String pass); //네임얻기 public String getName(String id);
MemberDao
@Override public boolean isLogin(String id, String pass) { // TODO Auto-generated method stub HashMap<String, String>map=new HashMap<String, String>(); map.put("id", id); map.put("pass", pass); int n=getSqlSession().selectOne("loginSuccess", map); return n==1?true:false; } @Override public String getName(String id) { // TODO Auto-generated method stub String name=getSqlSession().selectOne("nameByMember",id); return name; }
LoginController
다음처럼 주입시켜주고
@Autowired MemberDao dao;
//로그인처리 부분에서 value값 넣어주기
-> 이유는 @RequestParam이 true이므로 아이디 저장상태가 아닐땐 로그인 에러가 발생하기 때문이쥬
//로그인처리 @PostMapping("/login/loginproc") public String loginproc(HttpSession session, @RequestParam String id, @RequestParam String pass, @RequestParam(value="idsave",required = false) String idsave) //@RequestParam이 true이므로 아이디 저장상태가 아닐땐 로그인 에러 발생 { //아이디 저장 체크 안해도 에러 안나게 처리해준 것 return "redirect:login"; }
그리고 그 안에서 계속 추가 작성
//로그인처리 @PostMapping("/login/loginproc") public String loginproc(HttpSession session, @RequestParam String id, @RequestParam String pass, @RequestParam(value="idsave",required = false) String idsave) //@RequestParam이 true이므로 아이디 저장상태가 아닐땐 로그인 에러 발생 { //아이디 저장 체크 안해도 에러 안나게 처리해준 것 boolean sw=dao.isLogin(id, pass); //맞으면 세션에 3가지 저장 if(sw) { session.setMaxInactiveInterval(60*60*8); //8시간 동안 세션상태유지 생략하면 30분 유지 session.setAttribute("loginok", "yes"); session.setAttribute("idok", id); //아이디저장에 체크안하면 null값이므로 if(idsave==null) session.setAttribute("saveok", "no"); else session.setAttribute("saveok", "yes"); } //아이디와 비번이 맞으면 세션저장후 로그아웃폼으로 가야한다 //맞지않으면 경고메세지 출력후 다시 로그인 if(sw) return "redirect:login"; else return "/login/passFail"; }
비밀번호가 맞는 경우:)
비밀번호가 맞지 않는 경우:)
그리고 윗 부분으로 올라가서 다음 부분은 주석처리
@GetMapping("/login/login") public String loginform() { return "/login/loginForm"; }
다음과 같이 작성
@GetMapping("/login/login") public ModelAndView loginform(HttpSession session) { ModelAndView model=new ModelAndView(); String loginok=(String)session.getAttribute("loginok"); String id=(String)session.getAttribute("idok"); String save=(String)session.getAttribute("saveok"); if(loginok==null) { model.addObject("id", id==null?"":id); //처음 세션 사용했을 때 널값이면 대비하기 위해서 model.addObject("save",save==null || save.equals("no")?"no":"yes"); model.setViewName("/login/loginForm"); } else //로그인 성공 { String name=dao.getName(id); model.addObject("name", name); model.addObject("/login/logoutForm"); } return model; }
그리고 로그아웃한 상태를 추가로 작성해주어야 합니다:)
//로그아웃한 상태...로그아웃누르면 loginok는 지우고 idok는 남겨놓는다 @GetMapping("/login/logout") public String logout(HttpSession session) { session.removeAttribute("loginok"); //로그인을삭제 return "redirect:login"; }
logoutForm
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <div style="position: absolute; left: 200px; top: 150px;"> ${name}님이 로그인 중입니다 <input type="button" value="로그아웃" onclick="location.href='${path }/login/logout'"> </div> <img alt="" src="${path }/image/b7.png"> </body> </html>
이제 우리의 보완할점은
아이디 저장을 안눌렀는데도 로그아웃후 id가 남아있다는 점을 고쳐주어야 합니다:)
loginform
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <div class="container"> <form action="loginproc" method="post"> <table class="table table-hover" style="width: 400px;"> <caption>세션로그인</caption> <tr> <th>아이디</th> <td> <c:if test="${save=='yes' }"> <input type="text" name="id" size="10" placeholder="아이디" required="required" class="form-control" value="${id }"></c:if> <c:if test="${save=='no' }"> <input type="text" name="id" size="10" placeholder="아이디" required="required" class="form-control"></c:if> <input type="checkbox" name="idsave" ${save=='yes'?"checked":"" }>아이디저장 </td> </tr> <tr> <th>비밀번호</th> <td> <input type="password" name="pass" size="10" placeholder="비밀번호" required="required"> </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="로그인"> <input type="button" value="회원가입" onclick="location.href='${path}/member/insertform'"> </td> </tr> </table> </form> </div> </body> </html>
이제 메뉴를 보완해봅시다:)
다음과 같이 만들어주시면 okay
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <%@taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %> <!DOCTYPE html> <html> <head> <c:set var="path" value="<%=request.getContextPath() %>"></c:set> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.5.1.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <title>Insert title here</title> </head> <body> <a href="${path }/home">Home </a> <a href="${path }/info/insertform">입력폼</a> <a href="${path }/info/list">목록</a> <a href="${path }/member/insertform">회원가입</a> <a href="${path }/member/list">회원목록</a> <a href="${path }/login/login"> <c:if test="${sessionScope.loginok==null }">로그인</c:if> <c:if test="${sessionScope.loginok==null }">로그아웃</c:if> </a> <c:if test="${sessionScope.loginok!=null }"> <b style="color: red;">${sessionScope.idok}</b>님이 로그인중 </c:if> </body> </html>
'IT일기(하반기) > SPRING' 카테고리의 다른 글
[spring] 게시판만들기 - 방명록편 (2) | 2020.07.09 |
---|---|
[spring] 사이트 만들기 -게시판 편 (0) | 2020.07.08 |
[spring] 제발 외우기 (0) | 2020.07.07 |
[spring] 사이트 만들기 (0) | 2020.07.06 |
[spring] 게시판 만들기 upload (0) | 2020.07.02 |