본문 바로가기
Website Production

spring 홈페이지 - (16) 로그인/로그아웃 작업 (feat.아이디 기억하기)

by GoodDayDeveloper 2021. 5. 7.
반응형

지난시간에 회원가입을 하였으니 이번엔 로그인을 해야겠죠!

 

우선 완료화면입니다.

대략 이런 흐름이며, 아래 자세히 설명되어 있습니다.

 

로그인 화면은 지난번 받았던 부트스트랩 파일에서 login.html을 사용하도록 하겠습니다.

 

회원가입 포스팅을 한달만에 쓰는 거니... 이 강아지를 한달만에 보는거네요... 

볼때마다 깜짝 놀랍니다... 머 어째꺼나 이 디자인 가지고 사용할 예정입니다.

 

 

login.html
0.00MB

 

그리고 지난번에 만들었던 account에서 login.jsp에 이 html 파일을 넣어줍니다.

 

 

login.jsp

 

링크나 src에 css나 js의 경로를 찾기 위해서 /resources/ 를 붙여줘야 합니다.

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>SB Admin 2 - Login</title>
<!-- Custom fonts for this template-->
<link href="/resources/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<!-- Custom styles for this template-->
<link href="/resources/css/sb-admin-2.min.css" rel="stylesheet">
</head>
<body class="bg-gradient-primary">
<div class="container">
<!-- Outer Row -->
<div class="row justify-content-center">
<div class="col-xl-10 col-lg-12 col-md-9">
<div class="card o-hidden border-0 shadow-lg my-5">
<div class="card-body p-0">
<!-- Nested Row within Card Body -->
<div class="row">
<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>
<div class="col-lg-6">
<div class="p-5">
    <div class="text-center">
        <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1>
    </div>
    <form class="user">
        <div class="form-group">
            <input type="email" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Enter Email Address...">
        </div>
        <div class="form-group">
            <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password">
        </div>
        <div class="form-group">
            <div class="custom-control custom-checkbox small">
                <input type="checkbox" class="custom-control-input" id="customCheck"> <label class="custom-control-label" for="customCheck">Remember Me</label>
            </div>
        </div>
        <a href="index.html" class="btn btn-primary btn-user btn-block"> Login </a>
        <hr>
        <a href="index.html" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Login with Google
        </a> <a href="index.html" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Login with Facebook
        </a>
    </form>
    <hr>
    <div class="text-center">
        <a class="small" href="forgot-password.html">Forgot Password?</a>
    </div>
    <div class="text-center">
        <a class="small" href="register.html">Create an Account!</a>
    </div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="/resources/vendor/jquery/jquery.min.js"></script>
<script src="/resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/resources/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/resources/js/sb-admin-2.min.js"></script>
</body>
</html>
 
cs

 

 

 

그리고 뷰화면을 확인하기 위해 AccountController에 login 컨트롤러를 만들어줍니다.

 

AccountController

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.spring.web.account.web;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
import com.spring.web.account.service.AccountService;
 
@Controller
public class AccountController {
    
    @Autowired
    private AccountService accountService;
    
    @RequestMapping(value = "/account/login", method = RequestMethod.GET)
    public String login() {
        
        return "/account/login";
    }
 
}
cs

 

 

그러면 뷰화면에 우리가 붙여 넣은 디자인을 볼 수 있습니다.

 

여기서는 라이브러리 사용이 아닌 기본적인 로그인 프로그램 코드만을 취급하기 때문에 구글/페이스북 로그인은

제외시키고. 이자리에 비밀번호/ 회원가입/메인 화면 전환을 넣겠습니다.

enter email address는 enter id로 변경합니다.

그리고 a태그에 각각 링크를 답니다. 아이디/비밀번호찾기는 아직 구현안했으니 #으로 표기하도록 하죠

 

 

login.jsp (수정)

 

frmcheck 함수를 통해서 아이디/비밀번호 유효성 검사를 하고 이상없으면 서브밋을 통하여 login_action으로 보내줍니다.

또, id와 name에 컬럼 값을 넣어줍니다.

 

그리고 아이디 기억하기 기능입니다.

체크박스 값을 설정하기 위해 쿠키값이 비어 있지 않으면 체크값을 설정한 다음,

<c:if test="${not empty rememberCookie.getValue()}">
<c:set value="checked" var="checked" />
</c:if>

 

체크박스에 ${checked} 을 선언하여 값이 있을 경우만 체크될 수 있도록 합니다.

<input type="checkbox" class="custom-control-nput" id="customCheck" name="customCheck" valeu="true" ${checked} />

 

그리고 아이디 입력 input 소스에 value값을 쿠키값으로 설정합니다.

<input type="text" class="form-control form-control-user" id="me_id" name="me_id" aria-describedby="emailHelp" placeholder="Enter Id..." value="${rememberCookie.getValue() }"/>

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>                                                                                                            
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>                                                                                                                                  
<!DOCTYPE html>                                                                                                                                                                                   
<html>                                                                                                                                                                                            
<head>                                                                                                                                                                                            
                                                                                                                                                                                      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>                                                                                                          
<script type="text/javascript">                                                                                                                                                                   
$(function(){                                                                                                                                                                                     
var msg = "${msg}";                                                                                                                                                                             
if(msg != ""){                                                                                                                                                                                  
alert(msg);                                                                                                                                                                                      
}                                                                                                                                                                                               
});                                                                                                                                                                                               
                                                                                                                                                                                      
function frmCheck() {                                                                                                                                                                             
if ($("#me_id").val() == "") {                                                                                                                                                                  
alert("아이디를 입력해주세요.");                                                                                                                                                              
$("#me_id").focus();                                                                                                                                                                          
return false;                                                                                                                                                                                 
}                                                                                                                                                                                               
if ($("#me_pwd").val() == "") {                                                                                                                                                                 
alert("비밀번호를 입력해주세요.");                                                                                                                                                            
$("#me_pwd").focus();                                                                                                                                                                         
return false;                                                                                                                                                                                 
}                                                                                                                                                                                               
$("#loginform").submit();                                                                                                                                                                       
}                                                                                                                                                                                                 
</script>                                                                                                                                                                                         
<meta charset="utf-8">                                                                                                                                                                            
<meta http-equiv="X-UA-Compatible" content="IE=edge">                                                                                                                                             
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">                                                                                                            
<meta name="description" content="">                                                                                                                                                              
<meta name="author" content="">                                                                                                                                                                   
<title>SB Admin 2 - Login</title>                                                                                                                                                                 
<!-- Custom fonts for this template-->                                                                                                                                                            
<link href="/resources/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">                                                                                                 
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">                                                      
<!-- Custom styles for this template-->                                                                                                                                                           
<link href="/resources/css/sb-admin-2.min.css" rel="stylesheet">                                                                                                                                  
</head>                                                                                                                                                                                           
<body class="bg-gradient-primary">                                                                                                                                                                
<div class="container">                                                                                                                                                                         
<!-- Outer Row -->                                                                                                                                                                            
<div class="row justify-content-center">                                                                                                                                                          
<div class="col-xl-10 col-lg-12 col-md-9">                                                                                                                                                      
<div class="card o-hidden border-0 shadow-lg my-5">                                                                                                                                           
<div class="card-body p-0">                                                                                                                                                                 
<!-- Nested Row within Card Body -->                                                                                                                                                      
<div class="row">                                                                                                                                                                         
<div class="col-lg-6 d-none d-lg-block bg-login-image"></div>                                                                                                                           
<div class="col-lg-6">                                                                                                                                                                  
<div class="p-5">                                                                                                                                                                     
    <div class="text-center">                                                                                                                                                           
        <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1>                                                                                                                              
    </div>                                                                                                                                                                              
    <form id="loginform" action ="/account/login_action" method="post">                                                                                                          
    <c:if test="${not empty rememberCookie.getValue()}">                                                                                                                                
        <c:set value="checked" var="checked" />                                                                                                                                           
    </c:if>                                                                                                                                                                             
        <div class="form-group">                                                                                                                                                          
            <input type="text" class="form-control form-control-user" id="me_id" name="me_id" aria-describedby="emailHelp" placeholder="Enter Id..." value="${rememberCookie.getValue() }"/>
        </div>                                                                                                                                                                            
        <div class="form-group">                                                                                                                                                          
            <input type="password" class="form-control form-control-user" id="me_pwd" name="me_pwd" placeholder="Password" />                                                               
        </div>                                                                                                                                                                            
        <div class="form-group">                                                                                                                                                          
                       <div class="custom-control custom-checkbox small">                                                                                                             
                           <input type="checkbox" class="custom-control-input" id="customCheck" name="customCheck" valeu="true" ${checked} />                                           
                           <label class="custom-control-label" for="customCheck">아이디 기억</label>                                                                                  
                       </div>                                                                                                                                                         
                   </div>                                                                                                                                                             
        <a href="#" class="btn btn-primary btn-user btn-block" onclick="return frmCheck();">로그인</a>                                                                                    
            <hr>                                                                                                                                                                            
            <a href="/account/register" class="btn btn-google btn-user btn-block">회원가입</a>                                                                                              
            <a href="#" class="btn btn-facebook btn-user btn-block">아이디/비밀번호 찾기</a>                                                                                                
            <a href="/" class="btn btn-warning btn-user btn-block">홈페이지</a>                                                                                                             
        </form>                                                                                                                                                                           
        <hr>                                                                                                                                                                              
    </div>                                                                                                                                                                              
</div>                                                                                                                                                                                
</div>                                                                                                                                                                                  
</div>                                                                                                                                                                                    
</div>                                                                                                                                                                                      
</div>                                                                                                                                                                                        
</div>                                                                                                                                                                                          
</div>                                                                                                                                                                                            
<!-- Bootstrap core JavaScript-->                                                                                                                                                                 
<script src="/resources/vendor/jquery/jquery.min.js"></script>                                                                                                                                    
<script src="/resources/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>                                                                                                                    
<!-- Core plugin JavaScript-->                                                                                                                                                                    
<script src="/resources/vendor/jquery-easing/jquery.easing.min.js"></script>                                                                                                                      
<!-- Custom scripts for all pages-->                                                                                                                                                              
<script src="/resources/js/sb-admin-2.min.js"></script>                                                                                                                                         
</body>                                                                                                                                                                                           
</html>                                                                                                                                                                                           
                                                                                                                                                                                      
 
cs

 

MemberVO (변수 추가)

 

아이디 기억하기에서 변수를 추가하였으니 VO에서도 변수를 추가해줍니다.

customCheck의 변수의 타입을 boolean으로 설정합니다.

기본값은 false이지만 아이디 기억하기를 체크하면 true로 변경되면서 쿠키를 저장할 용도로 사용할 예정입니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.spring.web.vo;
 
import java.io.UnsupportedEncodingException;
 
public class memberVO extends PageVO {
    
    private boolean customCheck;
    
   
    public boolean isCustomCheck() {
        return customCheck;
    }
    public void setCustomCheck(boolean customCheck) {
        this.customCheck = customCheck;
    }
    
}
 
cs

 

 

 

 

 

이젠 우리에게 맞는 포맷이 된 것 같네요~~

 

 

그리고 인터셉터를 통해서 세션을  설정을 해주는 작업을 합니다.

만약 게시판을 이용하다가 로그인을 하게 되었을 때, 로그인 후 게시판으로 이동하게 해줘야하기 때문이죠!

인터셉터 패키지와 자바파일을 생성합니다. 파일이름은 아무렇게나 정해도 괜찮습니다~

 

 

인터셉터 자바파일을 만든 다음 코드를 작성해주시면 됩니다. 여기서 주위할 점은

HandlerInterceptorAdapter를 상속하는 것과 

HandlerInterceptorAdapter에서 지원하는 3가지 메소드를 사용하는 방법입니다.

 

아래 3가지 메소드는 직역하기 쉽게 명시되어 있습니다. 

public boolean preHandle  - 컨트롤러가 작동하기 전 실행

public boolean postHandle  - 컨트롤러 처리가 끝나고 return 후 화면 처리 직전에 실행

public boolean afterCompletion  - 컨트롤러 처리가 끝나고 return 후 화면 처리 끝난 후에 메서드 실행

 

간단합니다. 기호에 맞게 사용하시면 됩니다~~ 

 

 

 

반응형

 

 

 

UrlInterceptor.java

 

저는 preHandle를 이용하여 로그인 페이지를 제외한 모든 페이지에서 아래 인터셉터를 작동시켜 url 정보를 가져오려합니다.

세션에 로그인정보가 없다면httpservletRequest를 통하여 url과 queryString을 가져옵니다.그리고 URL이란 이름으로 합쳐준 다음 세션에 넣어줍니다. (추후 action 컨트롤러에서 사용합니다.)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.spring.web.interceptor;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
 
public class UrlInterceptor extends HandlerInterceptorAdapter {
 
@Override
public boolean preHandle(HttpServletRequest request, 
    HttpServletResponse response,
    Object handler) throws Exception {
    
    HttpSession session = request.getSession();
    if(session.getAttribute("loginVO"== null) {
    
     String uri = request.getRequestURI();
     String query = request.getQueryString();
        
        if(query == null || query.equals("null")) {
            query = "";
        } else {
            query = "?" + query;
        }
        
        if(request.getMethod().equals("GET")) {
            request.getSession().setAttribute("URL", uri + query);
        }
    }    
    return true;
}
 
  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
          ModelAndView modelAndView) throws Exception {
      super.postHandle(request, response, handler, modelAndView);
  } 
   
}
 
 
cs

 

 

servlet-context.xml

 

서블릿 xml에 자바 파일에 대한 빈 설정과 인터셉터 등록을 해줍니다.

여기서 mapping path는 적용할 부분이고, (저는 별을 사용하여 모든 공간을 설정하였습니다.)

exclude-mapping path는 제외할 부분을 설정합니다.

그리고 beans:ref bean에 빈의 id값을 넣어주면 적용이 됩니다.

 

1
2
3
4
5
6
7
8
9
<beans:bean id="UrlInterceptor" class="com.spring.web.interceptor.UrlInterceptor"/>
<interceptors>
  <interceptor>
    <mapping path="/**/**"/>
    <exclude-mapping path="/resources/**"/>
    <exclude-mapping path="/account/**"/>
    <beans:ref bean="UrlInterceptor"/>
  </interceptor>
</interceptors>
cs

 

 

서비스부터 mapper까지는 지나가겠습니다~

 

AccountService

 

1
2
memberVO actionLogin(memberVO searchVO);
void updateLastLogin(memberVO searchVO);
cs

 

AccountServiceImpl

 

1
2
3
4
5
6
7
8
9
@Override
public memberVO actionLogin(memberVO searchVO) {
return mapper.actionLogin(searchVO);
}
 
@Override
public void updateLastLogin(memberVO searchVO) {
mapper.updateLastLogin(searchVO);
}
cs

 

AccountMapper

 

1
2
memberVO actionLogin(memberVO searchVO);
void updateLastLogin(memberVO searchVO);
cs

 

 

XML

엑션로그인은 아이디값과 비밀번호를 조회해주며,

update는 마지막 로그인한 시간을 컬럼에 업데이트해줍니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<select id="actionLogin" parameterType="com.spring.web.vo.memberVO" resultType="com.spring.web.vo.memberVO">
<![CDATA[
    select
        *
    from
        tbl_member
    where
        me_id = #{me_id}
    and
        me_pwd = #{me_pwd}
]]>    
</select>
 
<update id="updateLastLogin" parameterType="com.spring.web.vo.memberVO" >
    UPDATE 
        tbl_member 
    SET 
        me_latest_login = sysdate()
    WHERE 
        me_id=#{me_id}
</update>
cs

 

 

AccountController.java

 

 

 

여기서는 패스워드를 암호화해서

조회한다음

로그인이 아닐 경우 실패하였다는 메세지와 함께 로그인페이지로 리다이렉트합니다.

그리고 쿠키를 만들고 앞에 CustomCheck라는 이름값을 만든다음 아이디를 값에 넣어줍니다.

아이디 기억하기를 눌렀을 경우 customcheck값이 true일테고 그럴 경우 7일동안 쿠키를 유지시킵니다.

아니면 0으로 설정하구요.

그리고 addcookie에 쿠키값을 담아줍니다.

 

세션에 memberVO를 직접 담아주면 보안면에서 좋지 않기에 별도의 VO를 만들어 사용하는것이 일반적입니다.

저는 loginVO라는 녀석을 사용하겠습니다.

memberVO의 값을 loginVO에 넣어줍니다.

그리고 session.setAttribute로 세션값을 넣어줍니다.

또한, 로그인한 시간을 업데이트해줍니다.

그리고 인터셉터에서 담은 URL값을 URL 변수에 넣어주고 

값이 있을 경우 requestURL에 넣어줍니다.

 

리다이렉트 return 값을 requestURL로 보내면 됩니다.

 

LoginVO (신규 생성)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.spring.web.vo;
 
 
public class LoginVO extends PageVO {
    
    private int idx;
    private String name;
    private String id;
    private String pwd;
    private String auth;
    private String email;    
    private String tel;
    private String latest_login;
    private String regdate;
    private String requestURL;
    
    
    
    public int getIdx() {
        return idx;
    }
    public void setIdx(int idx) {
        this.idx = idx;
    }
    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 getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getAuth() {
        return auth;
    }
    public void setAuth(String auth) {
        this.auth = auth;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getLatest_login() {
        return latest_login;
    }
    public void setLatest_login(String latest_login) {
        this.latest_login = latest_login;
    }
    public String getRegdate() {
        return regdate;
    }
    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }
    public String getRequestURL() {
        return requestURL;
    }
    public void setRequestURL(String requestURL) {
        this.requestURL = requestURL;
    }
}
cs

 

 

 

/account/login_action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@RequestMapping(value = "/account/login_action", method = RequestMethod.POST)
  public String actionLogin(
          @ModelAttribute("searchVO") memberVO searchVO,
          HttpServletRequest request,
          HttpSession session,
          RedirectAttributes redirectAttributes,
          HttpServletResponse httpServletResponse,
          ModelMap model) throws Exception {
    
 
    String encrypt = encryptPassword(searchVO.getMe_pwd().trim());
    searchVO.setMe_pwd(encrypt);
    
    memberVO loginInfo = accountService.actionLogin(searchVO);
    
    if(loginInfo == null){
        redirectAttributes.addFlashAttribute("msg""로그인을 실폐하였습니다.");
        return "redirect:/account/login.do";
    }
    
    Cookie rememberCookie = new Cookie("CustomCheck", loginInfo.getMe_id());
        rememberCookie.setPath("/");
        if(searchVO.isCustomCheck()) {
            rememberCookie.setMaxAge(60*60*24*7);
        } else {
            rememberCookie.setMaxAge(0);
        }
        httpServletResponse.addCookie(rememberCookie);
        
    
    LoginVO loginVO = new LoginVO();
    loginVO.setId(loginInfo.getMe_id());
    loginVO.setName(loginInfo.getMe_name());
    loginVO.setPwd(loginInfo.getMe_pwd());
    loginVO.setAuth(loginInfo.getMe_auth());
    loginVO.setEmail(loginInfo.getMe_email());
    loginVO.setTel(loginInfo.getMe_tel());
    loginVO.setLatest_login(loginInfo.getMe_latest_login());
    loginVO.setRegdate(loginInfo.getMe_regdate());
 
    session.setAttribute("loginVO", loginVO);
 
    accountService.updateLastLogin(searchVO);
    
    Object URL = session.getAttribute("URL");
redirectAttributes.addFlashAttribute("msg", "로그인에 성공했습니다.");
    
    String requestURL = "/";
    if(StringUtils.isNotBlank((String) URL)) requestURL = (String)URL;
 
    return "redirect:"+requestURL;
}
cs

 

 

 

 

/account/login

 

cookievalue의 value값이 customcheck인 rerememberCookie이 널이 아니면

model로 값을 뷰로 넘겨줍니다.

 

1
2
3
4
5
6
7
8
9
10
@RequestMapping(value = "/account/login", method = RequestMethod.GET)
public String login(HttpServletRequest request, Model model,
        memberVO searchVO, @CookieValue(value="CustomCheck", required=false) Cookie rememberCookie) {
    
    if(rememberCookie!=null) {
        model.addAttribute("rememberCookie", rememberCookie);
      }
    
    return "/account/login";
}
cs

 

 

/account/logout

 

로그아웃도 만들어줘야겠죠!

일단 세션을 지우기 전에 세션을 통해 URL 값을 받습니다.

그리고 3가지 세션 없애는 메서드를 통해 확실히 세션값을 지우도록 합니다.

status.setComplete();
session.removeAttribute("loginVO");
session.invalidate();

로그아웃할때도 홈이 아닌 로그아웃 버튼 누른 페이지로 갈 수 있도록 리다이렉트 설정해줍니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping(value = "/account/logout" , method = RequestMethod.GET)
  public String logout(
          HttpServletRequest request,
          SessionStatus status,
          HttpSession session,
          HttpServletResponse httpServletResponse,
          ModelMap model)  throws Exception {
    
    Object URL = session.getAttribute("URL");
 
    status.setComplete();
    session.removeAttribute("loginVO");
     session.invalidate();
    
    String requestURL = "/";
    if(StringUtils.isNotBlank((String) URL)) requestURL = (String)URL;
 
    return "redirect:"+requestURL;
}
cs

 

 

 

 

 

HomeController

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Controller
public class HomeController {
    
    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, HttpServletRequest request, Model model, HttpSession session) {
        
        
        LoginVO loginVO = (LoginVO) session.getAttribute("loginVO");
        model.addAttribute("loginVO",loginVO);
        
        Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
        if(null != inputFlashMap) {
            
            model.addAttribute("msg",(String) inputFlashMap.get("msg"));
            
        }
        
        return "home";
    }
    
}
 
cs

 

홈컨트롤러에 로그인 정보를 담은 loginVO를 세션에서 가져와서 model.addattribute로 빼내줍니다.

 

 

 

 

 

 

header.jsp

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
 
<c:choose>
    <c:when test="${loginVO eq null}">
        <a href="${pageContext.request.contextPath}/account/login" class="btn btn-primary btn-icon-split" style="width:auto; height:50px; margin-top:10px; margin-right:5px; text-align:center;">
         <span class="icon text-white-50">
             <i class="fas fa-flag"></i>
         </span>
         <span class="text">로그인</span>
     </a>
    <a href="${pageContext.request.contextPath}/account/register" class="btn btn-success btn-icon-split" style="width:auto; height:50px; margin-top:10px;">
        <span class="icon text-white-50">
            <i class="fas fa-check"></i>
        </span>
        <span class="text">회원가입</span>
    </a>    
    </c:when>
    <c:otherwise>
        <a href="${pageContext.request.contextPath}/account/logout" class="btn btn-primary btn-icon-split" style="width:auto; height:50px; margin-top:10px; margin-right:5px; text-align:center;">
         <span class="icon text-white-50">
             <i class="fas fa-flag"></i>
         </span>
         <span class="text">로그아웃</span>
     </a>
    </c:otherwise>
</c:choose>
 
cs

header.jsp에서는 jstl를 사용하기 위해서 맨 위에 jstl/core를 선언하고 

로그인 정보가 없으면 로그인/회원가입,

있으면 로그아웃이 나오도록 설정합니다.

 

 

 

 

 

 

완료 화면

 

 

게시판 글을 보다가 로그인 하면 게시판글로 돌아가고

로그아웃 후, 로그인을 누르면 아이디 기억이 되는 것을 알 수 있습니다.

 

 

 

 


 

항목을 클릭하시면 해당 페이지로 이동합니다.
Spring 웹 홈페이지 개발 과정 리스트 (1) 자바설치 및 환경변수 설정
(2) 이클립스 및 스프링 설치
(3) 톰캣설치 방법
(4) 이클립스 자바 환경설정 및 인코딩 설정방법
(5) 데이터베이스(Mysql) 설치
(6) 프로젝트 환경설정
(7) 홈페이지 디자인 적용
(8) 게시판 목록 페이지 작업
(9) 게시판 등록 페이지 작업
(10) 게시판 상세보기 페이지 작업
(11) 게시판 수정/삭제 페이지 작업
(12) 게시판 검색 페이지 작업
(13) 게시판 페이징 작업
(14) 게시판 페이징 쿼리스트링 작업
(15) 회원가입 작업 (feat.아이디 중복체크/비밀번호 암호화)
(16) 로그인/로그아웃 작업 (feat.아이디 기억하기)
(17) 아이디&비밀번호 찾기
(18) 마이페이지 정보&비밀번호 수정

 

 

 

반응형

댓글