16. BLOG만들기-로그인

박선규's avatar
Jan 30, 2024
16. BLOG만들기-로그인
 

1. 로그인 페이지 확인

💡
form태그 atction은 해당 페이지가 실행 될 때 action값에 있는 페이지로 이동한다. action → 주소 name 값을 추가하지 않으면 null name 값을 추가하는데, 클라이언트가 값을 추가하지 않으면 공백이 날라간다. submit은 form태그를 제출 할 때 사용한다. form태그랑 submit이랑 짝꿍이다. 그러나 default로 있어서 안적어도 구현이 돼있다.
notion image
 
header Content-Type : application/x-www-form-urlencoded; charset=utf-8 body username=ssar&password=1234
 

2. form 태그와 input태그 정리하기

notion image

3.컨트롤러에서 클라이언트 정보 받기(나는 3번사용)

3.1 방법 1

notion image
notion image
 

3.2 방법 2

notion image
💡
HttpServletRequest는 어디에서 온거지?
notion image
 

3.3 방법 3

💡
DTO(Data Transfer Object, 데이터 전송 객체)란 프로세스 간에 데이터를 전달하는 객체를 의미합니다. 로그인 DTO는 로그인 할때 POST요청으로 하지만 get과 과정이 동일하다. 클라이언트가 dto로 서버에게 데이터(usernamE과 email을) 보내면 서버가 DB에서 조회 쿼리로 요청한 다음 DB가 다시 서버에게 객체(user_table의 한행)로 저장하고 객체로 반환 기본기는 조회 결과를entity로 받아 내는게 기본기다
notion image

요청 DTO

클라이언트가 서버 측으로 전송하는 데이터
notion image
notion image

응답 DTO (session으로 대체)

화면에 필요한 데이터
📌
로그인에서는 어차피 응답 dto가 필요가 없는게 set-cookie로 쿠키 내용(쿠키 이름 = 값)를 가져오기 때문이다. 한마디로 응답 dto 대체로 cookie를 사용 재 로그인시 cookie를 들고 감
 

4. 값 받기 테스트

notion image
 
notion image
📌
로그인 할 때 마다 입력하기 귀찮으니 위 사진 처럼 설정하면 입력하지 않아도 로그인 바에 값이 들어가 있다.
notion image
 

5. 컨트롤러의 책임 (유효성 검사)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>클라이언트가 요청을 잘못함 400</h1> </body> </html>
notion image
notion image
notion image
 

6. 모델 연결 (DB 요청)

notion image
public User findByUsernameAndPassword(UserRequest.LoginDTO requestDTO) { Query query = em.createNativeQuery("select * from user_tb where username=? and password=?", User.class); query.setParameter(1, requestDTO.getUsername()); query.setParameter(2, requestDTO.getPassword()); User user = (User) query.getSingleResult(); return user; }
 
notion image
 
 
User.class 를 적을 수 있는 이유는 User 엔티티가 구현되어 있어야 한다. 이렇게 되면 자동으로 User클래스에 Table 데이터를 파싱해서 담아준다.
notion image
 
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>인증되지 않았습니다. username 혹은 password가 틀림. 401</h1> </body> </html>
notion image
📌
session자체를 ioc에 뛰우는게 아니라 그림 설명처럼 session참조 변수가 ioc컨테이너에 띄어져있다. 그리고 이미 @RequiredArgsConstructor 어노테이션으로 이해 생성자가 만들어 진 상태라 ioc에 띄어져있는 상태라 꺼내 사용 하면 된다.
notion image
notion image
@PostMapping("/login") public String login(UserRequest.LoginDTO requestDTO){ System.out.println(requestDTO); // toString -> @Data if(requestDTO.getUsername().length() < 3){ return "error/400"; // ViewResolver 설정이 되어 있음. (앞 경로, 뒤 경로) } User user = userRepository.findByUsernameAndPassword(requestDTO); if(user == null){ // 조회 안됨 (401) return "error/401"; }else{ // 조회 됐음 (인증됨) session.setAttribute("sessionUser", user); // 락카에 담음 (StateFul) } return "redirect:/"; // 컨트롤러가 존재하면 무조건 redirect 외우기 }
notion image
notion image
notion image
게시글 우측 상단에 작성자 이름 있

자기 서랍(락카) 찾는 법

notion image
notion image
📌
네트워크 로그인에서 set -쿠키가 뜸
 
Share article
RSSPowered by inblog