Spring/inflearn

회원 웹 기능 - 등록

곽수진 2022. 8. 31. 00:46
반응형

package hello.hellospring.controller;

import hello.hellospring.domain.Member;
import hello.hellospring.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MemberController {

    private final MemberService memberService;

    @Autowired
    public MemberController(MemberService memberService){
        this.memberService = memberService;
    }

    @GetMapping("/members/new")
    public String createForm(){
        return "members/createMemberForm";
    }

    @PostMapping("/members/new")
    public String create(MemberForm form){
        Member member = new Member();
        member.setName(form.getName());

        memberService.join(member);

        return "redirect:/";
    }
}

@GetMapping("/members/new") : localhost:8080/members/new에 접속하면 members 폴더에 있는 createMemberForm.html이 화면에 뜸

 

 

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>회원가입</title>
</head>
<body>
  <div class="container">
    <form action="/members/new" method="post">
      <div class="form-group">
        <label for="name">이름</label>
        <input type="text" id="name" name="name" placeholder="이름을 입력하세요.">
      </div>
      <button type="submit">등록</button>
    </form>
  </div>
</body>
</html>

▶ 이름을 입력하고 등록 버튼을 클릭시 name값이 서버로 전송

 

 

package hello.hellospring.controller;

public class MemberForm {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

▶ 웹 등록 화면에서 데이터를 전달 받을 폼 객체

 

 

localhost:8080/members/new 접속한 모습

반응형