1. URL 보내기
- BoardController.java
@GetMapping("/list")
public String boardList1(HttpServletRequest request) throws Exception{
if(!loginCheck(request)){
return "redirect:/login/login?toURL="+request.getRequestURL(); // 로그인을 안했으면 로그인 화면으로 이동
}
return "boardList"; // 로그인을 한 상태이면, 게시판 화면으로 이동
}
- loginForm.jsp
<input type="text" name="id" value="${cookie.id.value}" placeholder="이메일 입력" autofocus>
<input type="password" name="pwd" placeholder="비밀번호">
<input type="text" name="toURL" value="${param.toURL}"> <%--URL보내기--%>
- 로그인을 하지 않은 상태로 Board를 들어가면...
- URL을 숨겨준다...
<input type="text" name="id" value="${cookie.id.value}" placeholder="이메일 입력" autofocus>
<input type="password" name="pwd" placeholder="비밀번호">
<input type="hidden" name="toURL" value="${param.toURL}"> <%--URL보내기--%>
- URL을 로그인창에서 숨기고, 주소창을 통해 받아온다.
@PostMapping("/login")
public String login(String id, String pwd, String toURL, boolean rememberId,
HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
System.out.println("id="+id);
System.out.println("pwd="+pwd);
System.out.println("rememberId="+rememberId);
// 1. id와 pwd를 확인
if(!loginCheck(id, pwd)) {
String msg = URLEncoder.encode("id 또는 pwd가 일치하지 않습니다.", "UTF-8");
// 2-1. 일치하지 않으면, loginForm으로 이동
return "redirect:/login/login?msg="+msg;
}
// 2-2. id와 pwd가 일치하면
// 세션 객체를 얻어오기
HttpSession session = request.getSession();
// 세션 객체에 id를 저장
session.setAttribute("id", id);
// 체크박스가 true이면
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. 홈으로 이동
toURL = toURL==null || toURL.equals("") ? "/" : toURL;
// toURL이 null이거나, 빈 문자열이면 홈으로 아니면 toURL로간다.
return "redirect:"+toURL;
}
private boolean loginCheck(String id, String pwd) {
return "asdf".equals(id) && "1234".equals(pwd);
}
- toURL이 null 혹은 빈 문자열이면 홈으로 아니면 toURL이 가리키는 곳으로 간다.
- 필터 등록
// 필터를 적용할 요청의 패턴 지정 - 모든 요청에 필터를 적용.
@WebFilter(urlPatterns="*")
public class PerformanceFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// 초기화 작업
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// 1. 전처리 작업
long startTime = System.currentTimeMillis();
// 2. 서블릿 또는 다음 필터를 호출
chain.doFilter(request, response);
// 3. 후처리 작업
HttpServletRequest req = (HttpServletRequest)request;
String referer = req.getHeader("referer");
String method = req.getMethod();
System.out.print("["+referer+"] -> "+ method +"["+req.getRequestURI()+"]");
System.out.println(" 소요시간="+(System.currentTimeMillis()-startTime)+"ms");
}
@Override
public void destroy() {
// 정리 작업
}
}
- 어디서 왔는지, 그리고 어떤방식으로 왔는지 표시해준다.
- 세션의 생존 주기는 짧아야한다...(서버에 부담이 가기 때문)
- 세션은 로그인 후에 생성되어도 된다 -> 로그인을 하지 않은 홈페이지부터 세션이 시작되는건 낭비...
- session = "true"(디폴트값) or session = "false" -> 세션이 있으면? 세션 생성을 하지 않는다.
- 세션이 없을땐? true는 세션 생성, false는 세션을 생성하지 않는다.
- session = "false"가 기존 세션에 영향을 미치지 않는다.
- index.jsp파일에 session = "false"를 추가
- loginForm.jsp에도 추가
- 쿠키가 허용되어있지만 쿠키가 생성되지 않는다.
- @CookieValue
@PostMapping("/login")
public String login(@CookieValue("id") String cookieId, String id, String pwd, String toURL, boolean rememberId,
HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
- 쿠키중에 id라는 이름의 값을 cookieId에 넘겨준다.
'Spring' 카테고리의 다른 글
35. 예외처리/이론 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.02.17 |
---|---|
34. 예외처리/실습 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.02.17 |
32. 콘솔 한글깨짐 오류 고치기 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.02.15 |
31. 세션(session)/실습(2) - 패스트캠퍼스 백엔드 부트캠프 3기 (3) | 2025.02.13 |
30. 세션(session)/실습(1) - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.02.10 |