<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<span>아이디 : </span>
<input type="text" name="id" />
</div>
<div>
<span>비밀번호 : </span>
<input type="text" name="password" />
</div>
<div>
<button>로그인</button>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span>아이디 : </span>
<input type="text" name="id">
</div>
<div>
<span>비밀번호 : </span>
<input type="text" name="password">
</div>
<div>
<button>회원가입</button>
</div>
</body>
</html>
package com.example.site2.domain.auth.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class AuthController {
@GetMapping("/join")
public String authJoinPage() {
return "auth/join";
}
@GetMapping("/login")
public String authLoginPage() {
return "auth/login";
}
}
실행하면 잘 나옴
응답코드를 보내기위 responseentity에 담아서 보냄
package com.example.site2.domain.auth.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.site2.domain.auth.dto.ReqJoinDTO;
@RestController
public class AuthControllerApiV1 {
// @RequestMapping -> get, post, put, delete를 다 가지고 있음.
@PostMapping("/join")
// body는 json데이터
// @RequestBody json을 자바 객체로 만들어줌 <-> @ResponseBody는 자바 객체를 json으로
// @RequestParam 특정 쿼리스트링을 가져옴 -> ex)?홍길동 주소에다가 변수를 만드는 것
// @PathVariable 특졍 경로를 가져오 -> /1, /2 경로를 만들때
public ResponseEntity<?> join(@RequestBody ReqJoinDTO dto){
System.out.println(dto.getJoinUserDTO().getId());
System.out.println(dto.getJoinUserDTO().getPassword());
return null;
}
//내가 가진 정보를 주는 거니까 login도 POST
}
package com.example.site2.domain.auth.dto;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class ReqJoinDTO {
// 치킨 가방 = ReqJoinDTO
// 치킨 상자 = JoinUserDTO
// 치킨 = JoinUserDTO안에 있는 것들
private JoinUserDTO joinUserDTO;
}
package com.example.site2.domain.auth.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.site2.domain.auth.dto.ReqJoinDTO;
import com.example.site2.model.user.entity.UserEntity;
import com.example.site2.model.user.repository.UserRepository;
@Service
@Transactional(readOnly = true)
public class AuthServiceApiV1 {
@Autowired // 스프링 IoC컨테이너 안에 있는 애들만 가져올 수 있음
private UserRepository userRepository;
public ResponseEntity<?> join(ReqJoinDTO reqJoinDTO){
UserEntity userEntity = new UserEntity(null, reqJoinDTO.getJoinUserDTO().getId(), reqJoinDTO.getJoinUserDTO().getPassword());
// insert into user values(...);
userRepository.save(userEntity); // save가 insert같은 역할을 함
return new ResponseEntity<>(
"회원가입에 성공했습니다",
HttpStatus.OK
);
}
}
package com.example.site2.domain.auth.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.site2.domain.auth.dto.ReqJoinDTO;
import com.example.site2.domain.auth.service.AuthServiceApiV1;
@RestController
public class AuthControllerApiV1 {
// @RequestMapping -> get, post, put, delete를 다 가지고 있음.
@Autowired
private AuthServiceApiV1 authServiceApiV1;
@PostMapping("/join") // 데이터를 삽입하거나 받거나
// body는 json데이터
// @RequestBody json을 자바 객체로 만들어줌 <-> @ResponseBody는 자바 객체를 json으로
// @RequestParam 특정 쿼리스트링을 가져옴 -> ex)?홍길동 주소에다가 변수를 만드는 것
// @PathVariable 특졍 경로를 가져오 -> /1, /2 경로를 만들때
public ResponseEntity<?> join(@RequestBody ReqJoinDTO dto){
// 200, 400 응답코드를 보내기 위해 ResponseEntity를 사용해서 보냄
ResponseEntity<?> responseEntity = authServiceApiV1.join(dto);
// System.out.println(dto.getJoinUserDTO().getId());
// System.out.println(dto.getJoinUserDTO().getPassword());
return responseEntity;
}
//내가 가진 정보를 주는 거니까 login도 POST
}
한번 더 send하면 오류 터짐
왜냐 아이디가 이미 있어서 중복이 되는거임
// DB에 넣기 전에 해당 id를 가진 유저가 있는지 찾고
// 있으면 이미 사용중인 아이디 입니다. 라는 메시지 보내기
Optional<UserEntity> userEntityOptional = userRepository.findById(reqJoinDTO.getJoinUserDTO().getId());
if (userEntityOptional.isPresent()) {
return new ResponseEntity<>(
"이미 사용중인 아이디 입니다.",
HttpStatus.BAD_REQUEST
);
}
400에러로 유저가 요청을 잘못함.
아이디를 입력안하면
// 유저가 제대로된 데이터를 보냈는지 확인
if (reqJoinDTO.getJoinUserDTO().getId() == null) {
return new ResponseEntity<>(
"아이디를 입력해주세요.",
HttpStatus.BAD_REQUEST);
}
빈값인데 성공해버림
들어옴 삭제
if (reqJoinDTO.getJoinUserDTO().getId().length() < 3) {
return new ResponseEntity<>(
"아이디를 3글자 이상 입력해주세요.",
HttpStatus.BAD_REQUEST);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span>아이디 : </span>
<input id="id" type="text">
</div>
<div>
<span>비밀번호 : </span>
<input id="password" type="text">
</div>
<div>
<button onclick="requestJoin()">회원가입</button>
</div>
</body>
<script>
const requestJoin = () => {
const idInputTag = document.getElementById("id");
const passwordInptuTag = document.getElementById("password");
if (idInputTag.value == "") {
alert("아이디를 입력해주세요");
return;
}
const dto = {
joinUserDTO : {
id : idInputTag.value,
password : passwordInptuTag.value
}
}
// request
fetch("/api/v1/auth/join",{
method : "POST",
headers : {
"Content-Type" : "application/json"
},
body : JSON.stringify(dto)
})
// reponse
.then(response => response.text()) // 무조건은 아니지만 대부분 통신에서 사용
// json으로 보내면 json, text로 보내면 text로
.then(result => {
alert(result);
});
}
</script>
</html>