Springboot

[SpringBoot] 13. 로그인 처리

Song hyun 2024. 8. 7. 17:16
728x90
반응형

[SpringBoot] 13. 로그인 처리

1. 로그인 화면 (SignIn.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<!-- header.jsp  -->
<%@ include file="/WEB-INF/view/layout/header.jsp"%>

<!-- start of content.jsp(xxx.jsp)   -->
<div class="col-sm-8">
	<h2>로그인</h2>
	<h5>Bank App에 오신걸 환영합니다</h5>
	<!-- 예외적으로 로그인은 보안 때문에 post로 던지자 -->
	<form action="/user/sign-in" method="post"> 
		<div class="form-group">
			<label for="username">username:</label>
			<input type="text" class="form-control" placeholder="Enter username" id="username" name="username" value="길동"  >
		</div>
		<div class="form-group">
			<label for="password">Password:</label>
			<input type="password" class="form-control" placeholder="Enter password" id="password" name="password" value="1234">
		</div>
		<button type="submit" class="btn btn-primary">로그인</button>
	</form>
</div>
<!-- end of col-sm-8  -->
</div>
</div>
<!-- end of content.jsp(xxx.jsp)   -->

<!-- footer.jsp  -->
<%@ include file="/WEB-INF/view/layout/footer.jsp"%>

 

 

2. 로그인 화면 이동 / 기능 처리(@GetMapping/@PostMapping)

	/*
	 * 로그인 화면 요청 
	 * 주소설계 : http://localhost:8080/user/sign-in
	 */
	@GetMapping("/sign-in")
	public String singInPage() {
		// 인증검사  x 
		// 유효성검사 x  
		return "user/signIn";
	}
	
	
	/**
	 * 로그인 요청 처리 
	 * 주소설계 : http://localhost:8080/user/sign-in
	 * @return
	 */
	@PostMapping("/sign-in")
	public String signProc(SignInDTO dto) {
		// 1. 인증 검사 x 
		// 2. 유효성 검사 
		
		if(dto.getUsername() == null || dto.getUsername().isEmpty()) {
			throw new DataDeliveryException(Define.ENTER_YOUR_USERNAME, HttpStatus.BAD_REQUEST);
		}
		if(dto.getPassword() == null || dto.getPassword().isEmpty()) {
			throw new DataDeliveryException(Define.ENTER_YOUR_PASSWORD, HttpStatus.BAD_REQUEST);
		}
		// 서비스 호출 
		User principal = userService.readUser(dto);
		// 세션 메모리에 등록 처리 
		session.setAttribute(Define.PRINCIPAL, principal);
		// 새로운 페이지로 이동 처리 
		// TODO - 계좌 목록 페이지 이동처리 예정 
		return "redirect:/index"; 
	}

 

 

3. 로그인 기능 - 쿼리문 전송

	public User readUser(SignInDTO dto) {
		// 유효성 검사는 Controller 에서 먼저 하자. 
		User userEntity = null;  // 지역 변수 선언 
		try {
			userEntity = userRepository.findByUsernameAndPassword(dto.getUsername(), dto.getPassword());
		} catch (DataAccessException e) {
			throw new DataDeliveryException("잘못된 처리 입니다.", HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (Exception e) {
			throw new RedirectException("알수 없는 오류", HttpStatus.SERVICE_UNAVAILABLE);
		}
		
		if(userEntity == null) {
			throw new DataDeliveryException("아이디 혹은 비밀번호가 틀렸습니다.", HttpStatus.BAD_REQUEST);
		}
		
		return userEntity;
	}

 

728x90
반응형