티스토리 뷰

반응형

Controller


UsersController

//회원가입 페이지 join.jsp 열람 요청
@RequestMapping(value="/join", method=RequestMethod.GET)
public ModelAndView join() throws Exception {

	//RestController에서는 modelandview에 담아서 보낸다.
	return new ModelAndView("user/join");
}

RestController에서는 view페이지를 열기위해 MoedelAndView를 사용한다. Controller에서는 String으로 보내면 view페이지로 이동한다.

@Controller와 @RestController의 차이

  • @Controller는 String을 받게 되면 뷰리졸버로 리턴한다. JSON객체를 뷰리졸버를 거치지 않고 클라이언트로 보내고 싶다면 리퀘스트 매핑 아래쪽에 @ResponseBody를 달아 보낸다.
  • @RestController에서는 뷰리졸버를 거치지 않고 다시 클라이언트에게 돌려준다. 내보내는 데이터를 자동으로 JSON형식으로 내보낼 수 있다. 응답할때도 JSON형태로 응답한다.
//회원가입(register) 처리 요청
@PostMapping("")
public String register(@RequestBody UsersVO user) throws Exception {

	usersService.register(user);
	return "joinSuccess";
}

두 번 쓸 것을 한 번에 간단히 처리하는 방법

  • @RequestMapping(value="", method=RequestMethod.Post) => @PostMapping("")
  • @RequestMapping(value="", method=RequestMethod.GET) => @GetMapping("")

 

회원가입에 성공하면 joinSuccess라는 문자열을 리턴하도록 한다.

 

 

Service


UsersService

클라이언트에서 받은 비밀번호가 바로 DAO로 들어가게 되면 비밀번호가 평문인 상태로 들어가게 된다. 보안을 위해 서비스단에서 비밀번호를 암호화 시킨다. 

<!-- Spring Security 모듈 -->		
<dependency>
	<groupId>org.springframework.security</groupId>
	<artifactId>spring-security-web</artifactId>
	<version>${org.springframework-version}</version>
</dependency>

Security를 사용하려면 pom.xml에 Spring Security 모듈을 추가적으로 설정해준다.

//회원 가입 처리
@Override
public void register(UsersVO user) throws Exception {
	
	//[회원 비밀번호를 인코딩 하기]
	//암호화하는데 사용하는 Security에서 제공하는 클래스를 사용
	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
	//회원의 정보는 컨트롤러가 user에 담아서 넘겨주었을 것이다.
	System.out.println("암호화 전 비밀번호 : " + user.getPw());
	//비밀번호를 암호화하기
	String securePw = encoder.encode(user.getPw());
	//암호화한 비밀번호를 다시 user객체에 저장하기
	user.setPw(securePw);
	System.out.println("암호화 후 비밀번호 : " + user.getPw());
	
	//[암호화시킨 후에 회원 등록 하기]
	usersDAO.register(user);
}

암호화 하는데 사용하는 Security가 제공하는 BCryptPasswordEncoder 클래스를 사용. 해당 클래스의 encoder 메소드를 사용해서 비밀번호를 암호화 한다.

Postman 테스트

 

 

 

View


join.jsp

//회원 가입 요청 처리
$('#join-btn-btn').click(function(e) {
	
	if(chk1 && chk2 && chk3 && chk4 && chk5) {
		
		
		//값을 객체에 담기
		const email = $('#user_email').val();
		const id = $('#user_id').val();
		const pw = $('#user_pw').val();
		const name = $('#user_name').val();
		
		//json객체에 담기
		const user = {
			email: email,
			id: id,
			pw: pw,
			name: name
		};
		
		//통신
		$.ajax({
			type: "POST",
			url: "/myapp/user",
			headers: {
				"Content-Type": "application/json",
				"X-HTTP-Method-Override": "POST"
			},
			dataType: "text",
			data: JSON.stringify(user),
			success: function(result) {
				console.log("result : " + result);
				if(result === "joinSuccess"){
					alert("회원가입 성공!");
					self.location = "/myapp";
				}
			}
		}); //통신끝
		
	} else {
		alert('입력정보를 다시 확인하세요.')
	}
	
});

 

반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함