728x90
반응형
컨트롤러에서 HttpSession 사용
- 요청 매핑 애노테이션 적용 메서드에 HttpSession 파라미터 추가
- 요청 매핑 애노테이션 적용 메서드에 HttpServletRequest 파라미터 추가 후, HttpServletRequest를 이용해서 HttpSession 구하기
요청 매핑 애노테이션 적용 메서드에 HttpSession 파라미터 추가
@GetMapping
public String form(LoginCommand loginCommand, HttpSession session) {
return "login/loginForm";
}
- 요청 매핑 애노테이션 적용 메서드에 HttpSession 파라미터가 존재할 경우 스프링 MVC는 컨트롤러의 메서드를 호출할 때 HttpSession 객체를 파라미터로 전달
- HttpSession 생성 전 새로운 HttpSession 생성하고 그렇지 않으면 기존에 존재하는 HttpSession을 전달
- 항상 HttpSession을 생성
HttpServletRequest를 이용해서 HttpSession 구하기 - getSession()
@PostMapping
public String submit(LoginCommand loginCommand, Errors erros, HttpServletRequest req){
HttpSession session = req.getSession();
...
}
- 필요할 때 HttpSession
LoginController
@Controller
@RequestMapping("/login")
public class LoginController {
private AuthService authService;
public void setAuthService(AuthService authService) {
this.authService = authService;
}
@GetMapping
public String form(LoginCommand loginCommand, HttpSession session) {
return "login/loginForm";
}
@PostMapping
public String submit(LoginCommand loginCommand, Errors errors, HttpSession session) {
new LoginCommandValidator().validate(loginCommand, errors);
if (errors.hasErrors()) {
return "login/loginForm";
}
try {
AuthInfo authInfo = authService.authenticate(loginCommand.getEmail(), loginCommand.getPassword());
System.out.println(authInfo.getName());
//세션에 정보담기
session.setAttribute("authInfo", authInfo);
return "login/loginSuccess";
} catch (WrongIdPasswordException e) {
errors.reject("idPasswordNotMatching");
return "login/loginForm";
}
}
}
AuthInfo의 객체 정보를 HttpSession의 authInfo 속성에 저장
main.jsp
<%@ page contentType="text/html; charset=utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>메인</title>
</head>
<body>
<c:if test="${empty authInfo}">
<p>환영합니다.</p>
<p>
<a href="<c:url value="/register/step1" />">[회원 가입하기]</a>
<a href="<c:url value="/login" />">[로그인]</a>
</p>
</c:if>
<c:if test="${! empty authInfo}">
<p>${authInfo.name}님, 환영합니다.</p>
<p>
<a href="<c:url value="/edit/changePassword" />">[비밀번호 변경]</a>
<a href="<c:url value="/logout" />">[로그아웃]</a>
</p>
</c:if>
</body>
</html>
LoginController에서 로그인 성공 할 경우 HttpSession의 authInfo 속성에 인증 정보 객체 저장하고
출력하게 한다.
728x90
반응형
'Spring' 카테고리의 다른 글
[Spring] 쿠키 사용하기 (0) | 2024.05.25 |
---|---|
[Spring] 인터셉터 사용해보기 (0) | 2024.05.22 |
[Spring] Bean Validation 검증 (0) | 2024.05.18 |
[Spring] 컨트롤러 범위 Validator @InitBinder (0) | 2024.05.18 |
[Spring] 글로벌 Validator (0) | 2024.05.14 |