3층 1구역 - 개발의 장/Spring

Spring - 세션을 이용하여 로그인해보는 퀴즈(2022-10-18)

상이태상 2022. 10. 18. 12:37

1. 서론

세션을 이용해서 로그인을 해보도록 하자.

 

세션을 이용하여 로그인하는 퀴즈(session/index, login, SessionQuizController)

 

2.본론

SessionQuizController.java

 

package com.care.cs.session;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class SessionQuizController {
	@Autowired private HttpSession session;
	
	@RequestMapping("session/index")
	public void index() {}
	
//	로그인 폼을 보여주기 위한 get맵핑
	@GetMapping("session/login")
	public void login() {}
	
//	아이디 비밀번호 검증을 위한 post맵핑
	@PostMapping("session/login")
	public String login(String id, String pw) {
		if("admin".equals(id) && "1234".equals(pw)) {
		session.setAttribute("id", "admin");
		session.setAttribute("pw", "1234");
		return "redirect:index";
		}
		return "session/login";
	}
	
	@RequestMapping("session/logout")
	public String logout() {
		session.invalidate();
		return "redirect:index";
	}
	
}

 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>인덱스 페이지</title>
<!-- http://localhost:8085/cs/session/index -->
</head>
<body>

	<h1>인덱스 페이지</h1>
	<br>
	<br>
	<c:choose>
		<c:when test="${empty sessionScope.id }">
			<a href="login">로그인</a>
		</c:when>
		<c:otherwise>
			<a href="logout">로그아웃</a><br>
		</c:otherwise>
	</c:choose>
</body>
</html>

 

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>로그인 하기</title>
</head>
<body>
<h3>로그인 페이지</h3>
<form action="login" method="post">
	<input type="text" name="id" placeholder="아이디" /> <br>
	<input type="password" name="pw" placeholder="비밀번호" /><br>
	<input type="submit" value="로그인" />
	<input type="button" value="취소" onclick="location.href='index'" />
</form>
</body>
</html>

 

3. 결론

어느 정도 흐름을 파악하고 나니 코드 작성하는게 삐걱거리긴 해도 작성은 되는 느낌이다.

아............마도??

연습 하다 보면 익숙해지겠지