아이뒤 비밀번호 입력시 db에 있다면 로그인
- 세션 로그인

1.Controller
@PostMapping("/login")
public String login(@Valid UserRequest.LoginDTO loginDTO, Errors errors) {
User sessionUser = userSerivce.로그인(loginDTO);
session.setAttribute("sessionUser", sessionUser);
//TODO 주헌
//session.setAttribute();
return "redirect:/";
}
2.User
package shop.mtcoding.filmtalk.user;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import java.sql.Timestamp;
@Getter
@Setter
@Table(name = "user_tb")
@NoArgsConstructor
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;//아이디
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
@Column
private String phone;
@CreationTimestamp
private Timestamp createdAt;
@Builder
public User(Long id, String username, String password, String email,String phone, Timestamp createdAt) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
this.createdAt = createdAt;
}
}
service
public User 로그인(UserRequest.LoginDTO loginDTO) {
User user = userQueryRepository.findByUsernameAndPassword(loginDTO.getUsername(), loginDTO.getPassword());
return user;
}
repository
public User findByUsernameAndPassword(String username, String password) {
Query query = em.createQuery("select u from User u where u.username=:username and u.password =:password", User.class);
query.setParameter("username", username);
query.setParameter("password", password);
try {
User user = (User) query.getSingleResult();
return user;
} catch (Exception e) {
throw new Exception401("인증되지 않았습니다.");
}
}
인증되지 않으면 예외처리 진행
Share article