Spring을 공부시작을 3주정도 지난것 같다.
처음에 시작했을때 많이 어렵다고 생각하였으나 Service flow를 그림으로 그리면서 공부하니 훨씬 이해하기 쉽고 특정부분에서 어떠한 것이 필요한가 이해하기 쉬웠다. 이 코드는 이전에 진행했던 게시판에서 한 Section만 작성한 코드이다.(이전 게시판은 음악리뷰 게시판)
(디자인 부분은 신경쓰지 않았습니다. 기능만 구현하였습니다.)
1. 로그인하기
어떠한 하나의 패키지를 만들때 가장 기본적으로 들어가야하는것은 다음과 같다.
예를 들어 지금 로그인 부분에서 User라는 Package가 있다면 그 안에 필수 요소는 User, UserRepository, UserController 이렇게 3개의 요소가 가장 기본이다.
기능은 1. 기존의 사용자가 로그인을하는 경우 2.회원가입을 하는 경우 라고 생각한다.
User --> 값에 _ 가 들어가면 안된다 나중에 Repository에서 찾을때 _가 있으면 찾지 못한다!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
package com.jeongmin.music.User;
import javax.persistence.*;
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userId;
private String userName;
private String userPassword;
public void setId(Long id) {
this.id = id;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Long getId() {
return id;
}
public String getUserId() {
return userId;
}
public String getUserName() {
return userName;
}
public String getUserPassword() {
return userPassword;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
UserRepository --> 사용자를 찾기 위한 Query 부분
1
2
3
4
5
6
7
8
9
10
|
package com.jeongmin.music.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository <User,Long> {
User findByUserIdAndUserPassword(String userId,String userPassword); //Query부분
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
UserController -->여기를 이해하는것이 가장 중요!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
package com.jeongmin.music.User;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
private final UserJoinService userJoinService;
private final UserLoginService userLoginService;
public UserController(UserJoinService userJoinService, UserLoginService userLoginService)
{
this.userJoinService=userJoinService;
this.userLoginService=userLoginService;
}
@PostMapping(value = "/joinRequest")
public String joinRequest(HttpServletRequest request)
{
userJoinService.JoinService(request);
return "login";
}
@PostMapping(value = "/loginRequest")
public String loginRequest(HttpServletRequest request)
{
User user = userLoginService.loginService(request);
if(user==null)
{
return "login";
}
else
{
return "board";
}
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
PasswordHash --> String으로 받은 사용자의 비밀번호를 SHA를 사용부분 이부분이 궁금하면 따로 정리 해놓은 Posting 참조!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package com.jeongmin.music.User;
import org.springframework.stereotype.Service;
import java.security.MessageDigest;
@Service
public class PasswordHash {
public String getSHA256(String plainText) {
String shaString = "";
if(plainText == null){
return "";
}
try {
MessageDigest sh = MessageDigest.getInstance("SHA-256");
StringBuffer stringBuffer = new StringBuffer();
int byteSize = byteData.length;
for (int i = 0; i < byteSize; i++) {
}
shaString = stringBuffer.toString();
}
catch (Exception e) {
e.printStackTrace();
shaString = null;
}
return shaString;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
Service부분은 사용자를 로그인 Part의 UserLoginService, 회원가입 Part의 UserJoinService가 필요하다,
UserJoinService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package com.jeongmin.music.User;
import org.springframework.stereotype.Service;
@Service
public class UserJoinService {
private final UserRepository userRepository;
private final PasswordHash passwordHash;
public UserJoinService(UserRepository userRepository,PasswordHash passwordHash)
{
this.userRepository=userRepository;
this.passwordHash=passwordHash;
}
public void JoinService(HttpServletRequest request)
{
String name=request.getParameter("userName"); //이름
String id=request.getParameter("userId");//아이디
String password = request.getParameter("userPassword");//비밀번호
User user = new User();//객체생성
user.setUserName(name);
user.setUserId(id);
String HashPassword =passwordHash.getSHA256(password);
user.setUserPassword(HashPassword);
userRepository.save(user);//사용자 객체 저장
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
회원가입의 Service Flow는 다음과 같다.
회원가입 버튼을 눌렀을때 Post형식으로 /joinRequest를 UserController로 간다. UserController에서 /joiinRequest를 @PostMapping을하여 UserJoinService를 사용한다.
이 Service부분을 살표보면 HttpServletRequest를 사용하여 Front쪽에서 "userName", "userId", "userPassword" 값을 전달받아 객체를 생성하여 값을 Setting하여 Repository에 저장을 한다. 그다음 다시 로그인 창이 다시 뜨게 return을 해준다.
( 여기에서 비밀번호는 그냥 저장하면 안되기 때문에 PasswordHash를 써서 변경후 저장해야한다.)
위의 생성자는 @Autowired를 대신하여 생성자를 작성하였다. 이렇게 한 이유는 Spring Framework가 종속적이기 때문이다.
생성자의 인자가 많아지는 경우에 final을 받는 파라미터를 생성자로 만들어주는 @RequiredArgsConstructor을 사용가능함 . 다만 이때는 인자의 추가나 순서 변경시 생성자 클래스가 변경되는 점에 주의해야한다. --출처 우아한형제들 기술블로그
http://woowabros.github.io/experience/2019/02/28/pilot-project-settle.html
코드리뷰 적응기(feat. 파일럿 프로젝트) - 우아한형제들 기술 블로그
안녕하세요. 결제정산개발팀의 권세희입니다.저는 정산업무를 맡게 되었는데, 정산은 데이터 정합성과 트랜잭션, 도메인 주도 개발, Entity 간의 연관 관계, 대용량 데이터 처리가 핵심인 시스템입니다.정산 도메인과 기술셋에 대한 경험이 없어 들어가기에 앞서 파일럿 프로젝트를 먼...
woowabros.github.io
UserLoginService
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package com.jeongmin.music.User;
import org.springframework.stereotype.Service;
@Service
public class UserLoginService {
private final UserRepository userRepository;
private final PasswordHash passwordHash;
private final HttpSession session;
public UserLoginService(UserRepository userRepository, PasswordHash passwordHash, HttpSession session){
this.userRepository=userRepository;
this.passwordHash=passwordHash;
this.session=session;
}
public User loginService(HttpServletRequest request){
String id=request.getParameter("userId");
String password=request.getParameter("userPassword");
String hashPassword=passwordHash.getSHA256(password);
User user=userRepository.findByUserIdAndUserPassword(id,hashPassword);
session.setAttribute("user",user);
return user;
}
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
위의 UserJoinService를 이해하였다면 이 파트도 쉽게 이해할 수 있다 다만, 다른점이 있다면 Repository에 잇는 findByUserAndUserPassword를 사용하여 사용자를 찾아주고 찾아준 객체를 user객체에 저장 및 반환하여 Controller /loginRequest에서 반환한 값이 null일 경우에는 계속 로그인 페이지에 남고 로그인 성공시 다음 페이지로 넘어간다.
Front Part
Join.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>회원가입페이지</title>
<body>
<div class="login-box">
<h1>Create Account</h1>
<form action="/joinRequest" method="post">
<div class="textbox">
<input type="text" value ="이름을 입력해주세요" placeholder="Username" name="userName">
</div>
<div class="textbox">
<input type="text" value="아이디를 입력해주세요" placeholder="UserId" name="userId">
</div>
<div class="textbox">
<input type="password" value="비밀번호를 입력해주세요" placeholder="Password" name="userPassword">
</div>
<input class="btn" type="submit" value="Sign In">
</form>
</div>
</body>
</head>
<body>
<form>
</form>
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
login.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>로그인</title>
<body>
<div class="login-box">
<h1>Longin</h1>
<form action="/loginRequest" method="post">
<div class="textbox">
<i class="far fa-user"></i>
<input type="text" placeholder="UserId" name="userId">
</div>
<div class="textbox">
<i class="fas fa-lock"></i>
<input type="password" placeholder="Password" name="userPassword">
</div>
<input class="btn" type="submit" name="" value="Sign In">
</form>
<br>
<br>
</div>
</body>
</head>
<body>
<form>
</form>
</body>
</html>
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
'SpringBoot' 카테고리의 다른 글
사용중인 포트 찾아서 Kill하기 (0) | 2019.07.23 |
---|---|
Spring으로 만드는 간단한 게시판(2) (0) | 2019.07.22 |
Get & Post (0) | 2019.07.08 |
해시(Hash) 와 암호화(Encryption) (0) | 2019.07.08 |
쿠키(Cookie)와 세션(Session) (0) | 2019.07.08 |