스프링 - 간단한 회원 가입 개념
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<form action="${pageContext.request.contextPath}/join/step1" method="post">
<p> 이름 : <input type="text" name="name" value="${user.name}"> </p>
<p> 이메일 : <input type="text" name="email" value="${user.email}"> </p>
<p>
<button type="submit">다음단계</button>
</p>
</form>
</body>
</html>
- 입력 받은 값들을 서버로 보내야하니 form 태그로 감쌈
- 서브밋 버튼을 누르면 step1.jsp로 이동 방식은 post
- 이름과 이메일에 있는 value 값은 다음 단계에서 뒤로가기 했을때 작성했던 값들을 다시 보여주기 위함.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<form action="${pageContext.request.contextPath}/join/step2" method="post">
<p> 아이디 : <input type="text" name="id" value="${user.id}"> </p>
<p> 패스워드 : <input type="password" name="pwd"> </p>
<p> 전화번호 : <input type="text" name="tel" value="${user.tel}"> </p>
<p>
<p>
<button type="button" onclick="location.href='${pageContext.request.contextPath}/join/main';">이전단계</button>
<button type="submit">회원가입</button>
</p>
</form>
</body>
</html>
- 이전단계 버튼을 누르면 이전 페이지로 돌아가게 location.href=를 이용해서 주소를 넣어준다.
package com.sp.app.join;
public class User {
private String id;
private String name;
private String pwd;
private String email;
private String tel;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
User.java 파일
- 입력한 값들을 저장하는 용도
package com.sp.app.join;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
/*
* @SessionAttributes
* 모델의 객체를 세션에 저장하여 뷰(jsp)에서 공유
* Controller에서 사용함
* 용도
* - 스프링 form 태그 라이버리를 이용할 경우
* 여러 단계에 걸쳐 입력된 값을 처리할 경우
* double submit 방지함 - 뒤로가기 안되게함
*/
@SessionAttributes("user") // 세션에 유저의 객체를 저장함
@Controller("join.joinController")
@RequestMapping("/join/*")
public class JoinController {
@ModelAttribute("user") // 모든 페이지에서 생성할 수 있는 객체? 생성 (모든 페이지에서 유저 객체 공유)
public User command() {
return new User(); // 유저의 객체를 넘김
}
// @ModelAttribute("user")는 @SessionAttributes("user")에서 설정한
// 설정 이름이 동일하므로 세션에 저장된 user를 사용함
// User 클래스 명 첫글자가 소문자인 이름과 동일한 경우 생략 가능
@RequestMapping(value = "main", method = RequestMethod.GET)
public String joinForm(@ModelAttribute("user") User user) throws Exception {
// 회원가입 처음화면(step1.jsp) 출력
return "join/step1";
}
@RequestMapping(value = "step1", method = RequestMethod.POST)
public String step1Submit(@ModelAttribute("user") User user) throws Exception {
// 회원가입 두번째 화면 출력
return "join/step2";
}
@RequestMapping(value = "step2", method = RequestMethod.POST)
public String step2Submit(@ModelAttribute("user") User user,
SessionStatus sessionStatus,
Model model
) throws Exception {
// 회원가입 정보를 DB에 저장
String s = "아이디 : " + user.getId() + "<br>";
s += "이름 : " + user.getName() + "<br>";
s += "이메일 : " + user.getEmail() + "<br>";
s += "패스워드 : " + user.getPwd() + "<br>";
s += "전화번호 : " + user.getTel() + "<br>";
// 세션에 저장된 내용 지우기
sessionStatus.setComplete();
model.addAttribute("msg", s);
return "join/complete";
}
}
가장 중요한 컨트롤러
여기서 모든 컨트롤이 이루어짐
@SessionAttributes("user") 를 사용해야 뒤로가기 했을때 작성했던 값들을 볼 수 있다.
@RequestMapping("/join/*") 주소줄에 join/*을 통해서 들어오는 모든 요청은 여기로 오게끔 한다.
@ModelAttribute("user") // 모든 페이지에서 생성할 수 있는 객체? 생성 (모든 페이지에서 유저 객체 공유)
public User command() {
return new User(); // 유저의 객체를 넘김
}
이 코드가 있어야 아까만든 User.java의 객체를 생성하고 모든 페이지에서 이 유저 객체를 공유한다.
공유가 되어야 뒤로가기 했을때 작성했던 값을 보낼 수 있다.
아까 만든 세션의 user와 동일함.
@RequestMapping(value = "main", method = RequestMethod.GET)
public String joinForm(@ModelAttribute("user") User user) throws Exception {
// 회원가입 처음화면(step1.jsp) 출력
return "join/step1";
}
리퀘스트매핑 방식이 GET 방식이고 아까 작성했던 join/뒤에 값이 main이라면 (주소줄에 /join/main) 이라고 친다면
이 기능을 수행 하겠다 라는 뜻
데이터 전송은 보통 POST 방식으로 하니까 혹시 GET 방식으로 들어 왔다면 다시 처음 화면으로 돌아가게 한다 라는 뜻
@RequestMapping(value = "step1", method = RequestMethod.POST)
public String step1Submit(@ModelAttribute("user") User user) throws Exception {
// 회원가입 두번째 화면 출력
return "join/step2";
}
반대로 POST 방식으로 정상적으로 들어왔으면 두번째 창 step2를 열겠다
인자로 받는 @ModelAttribute("user") User user 의 뜻은 아까 만든 객체 공유를 위해서 앞에
@ModelAttribute("user")를 붙여주고 뒤에 User user는 User의 객체를 인자로 받겠다는 뜻
@RequestMapping(value = "step2", method = RequestMethod.POST)
public String step2Submit(@ModelAttribute("user") User user,
SessionStatus sessionStatus,
Model model
) throws Exception {
// 회원가입 정보를 DB에 저장
String s = "아이디 : " + user.getId() + "<br>";
s += "이름 : " + user.getName() + "<br>";
s += "이메일 : " + user.getEmail() + "<br>";
s += "패스워드 : " + user.getPwd() + "<br>";
s += "전화번호 : " + user.getTel() + "<br>";
// 세션에 저장된 내용 지우기
sessionStatus.setComplete();
model.addAttribute("msg", s);
return "join/complete";
}
이제 마지막 단계인 주소줄에 step2가 온다면 여기 기능을 수행한다
마찬가지로 인자로 @ModelAttribute("user") User user 를 받아야 하고,
세션 정보 저장을 위해서 SessionStatus sessionStatus 로 인자로 받고,
User 객체에 저장된 내용들 jsp에 쏘기 위해서 Model model도 필요하다.
이제 인자로 받은 객체를 통해서 값들을 정리하고
그 값들을 model.addAttribute("msg", s); 를 통해서 msg 라는 이름에 내용을 담는다.
그리고 마지막으로 sessionStatus.setComplete(); 한줄을 입력하면 세션에 저장된 내용이 지워진다.
모든 절차가 끝나면 complete 화면으로 보낸다.
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
</head>
<body>
<h3>환영 합니다.</h3>
<p>
${msg}
</p>
</body>
</html>
complete.jsp