โ๏ธ ์ฟ ํค๋ฅผ ์ ๋ฌ ๋ฐ๊ฒ ํด ์ฃผ๋ ์ ๋ํ ์ด์
โ๏ธ @CookieValue("id") String cookieID
@PostMapping("/login")
public String login(@CookieValue("id") String cookieID, ..) {
...
@PostMapping("/login")
public String login(@CookieValue("JSESSIONID") String sessionID, ...) {
๐ช JSP์์ ๋ฐฐ์ ๋ Cookie๋ฅผ Spring์์๋ ํ์ฉํด ๋ณด์.
โ๏ธ ์์ด๋ ๊ธฐ์ต์ ๋๋ฅด๋ฉด ์ฟ ํค ์ ์ฅ
โ๏ธ ์์ด๋ ๊ธฐ์ต์ ๋๋ฅด์ง ์์ผ๋ฉด ์ฟ ํค ์ญ์
package kr.ac.jipark09;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
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
@RequestMapping("/login")
public class LoginController {
@GetMapping("/login")
public String loginForm() {
return "loginForm";
}
@PostMapping("/login")
public String login(String id, String pwd, boolean rememberId, HttpServletResponse response) throws Exception {
// 1. id์ pwd๋ฅผ ํ์ธ
if(!loginCheck(id, pwd)) {
// 2-1. ์ผ์นํ์ง ์์ผ๋ฉด, index์ผ๋ก ์ด๋
String msg = URLEncoder.encode("id ๋๋ pwd๊ฐ ์ผ์นํ์ง ์์ต๋๋ค.", "utf-8");
return "redirect:/login/login?msg=" + msg;
}
// 2-2. id์ pwd๊ฐ ์ผ์นํ๋ฉด,
if(rememberId) {
// 1. ์ฟ ํค๋ฅผ ์์ฑ
Cookie cookie = new Cookie("id", id);
// 2. ์๋ต์ ์ ์ฅ
response.addCookie(cookie);
} else {
// ์ฟ ํค๋ฅผ ์ญ์
Cookie cookie = new Cookie("id", id); // ํน์ ์์ ์ฟ ํค๋ฅผ ์ญ์
cookie.setMaxAge(0);
response.addCookie(cookie);
}
// 3. ํ์ผ๋ก ์ด๋
return "redirect:/";
}
private boolean loginCheck(String id, String pwd) {
return "asdf".equals(id) && "1234".equals(pwd);
}
}
<form action="<c:url value='/login/login'/>" method="post" onsubmit="return formCheck(this);">
<h3 id="title">Login</h3>
<div id="msg">
<c:if test="${not empty param.msg}">
<i class="fa fa-exclamation-circle"> ${URLDecoder.decode(param.msg)}</i>
</c:if>
</div>
<input type="text" name="id" value="${cookie.id.value }" placeholder="์ด๋ฉ์ผ ์
๋ ฅ" autofocus>
<input type="password" name="pwd" placeholder="๋น๋ฐ๋ฒํธ">
<button>๋ก๊ทธ์ธ</button>
<div>
<label><input type="checkbox" name="rememberId" ${empty cookie.id.value ? "" : "checked"}> ์์ด๋ ๊ธฐ์ต</label> |
<a href="">๋น๋ฐ๋ฒํธ ์ฐพ๊ธฐ</a> |
<a href="">ํ์๊ฐ์
</a>
</div>
<script>
function formCheck(frm) {
let msg ='';
if(frm.id.value.length == 0) {
setMessage('id๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.', frm.id);
return false;
}
if(frm.pwd.value.length == 0) {
setMessage('password๋ฅผ ์
๋ ฅํด์ฃผ์ธ์.', frm.pwd);
return false;
}
return true;
}
function setMessage(msg, element){
document.getElementById("msg").innerHTML = ` ${'${msg}'}`;
if(element) {
element.select();
}
}
</script>
</form>
Reference
: https://fastcampus.co.kr/dev_academy_nks