Spring/[Spring]Survey(설문조사)

스프링 설문지 만들기 프로젝트 -2 (db저장)

Ms.Pudding 2022. 1. 9. 23:40

프레임워크 : 마이바티스 mybatis

view언어 : 타임리프 thymeleaf

 

1편에서는 설문조사 화면만 보여주고 submit하면 db가 저장이 안되었었다.

 

이제 제출 시 db에 저장되는 로직을 만들어보자.

 

1.html수정

자바스크립트를 추가해주고 value를 숫자로 수정해줘서 db저장될 때 숫자가 보이도록 해줌 

<html xmlns:th="http://www.thymeleaf.org" layout="http://www.ultraq.net.nz/thymeleaf/layout">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<!--2. jQuery 파일-->
<script src="https://code.jquery.com/jquery-3.4.1.js" type="text/javascript"></script>
<!--부트스트랩 연결코드 -->
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<!--css 연결 -->
<link rel="stylesheet" th:href="@{/css/survey/survey.css}" type="text/css">
<meta charset="UTF-8">

<Script>
$(document).ready(function(){
    var form = $(#survey);

    //submit 버튼 클릭 이벤트
    $("btnSubmit).on("click",function() {
    self.location = "/list";
    });

})

<!--html화면이 뜨면, survey가 id있는 부분이 실행되며 , submit버튼을 클릭하면 /lsit로 가는게 실행된다.


</Script>
<body>
<div class="container">
    <header class="header">
        <h1 id="title" class="text-center">Survey Form</h1>
        <p id="description" class="description text-center">
            submit your survey here
        </p>
    </header>
    <form id="survey" th:action ="@{list}" th:object="${surveyVO}" method="post">
        <div class="form-group">
            <label id="name-label" for="name">Name</label>
            <input
                    type="text"
                    name="writerName"
                    id="name"
                    class="form-control"
                    placeholder="Enter your name"
                    required
            />
        </div>
        <div class="form-group">
            <label id="email-label" for="email">Email</label>
            <input
                    type="email"
                    name="email"
                    id="email"
                    class="form-control"
                    placeholder="Enter your Email"
                    required
            />
        </div>

        <!--question1 -->
        <div class="form-group">
            <p>question1</p>
            <label>
                <input
                        name="question1"
                        value=1
                        type="radio"
                        class="input-radio"
                        checked
                />answer1</label
            >
            <label>
                <input
                        name="question1"
                        value=2
                        type="radio"
                        class="input-radio"
                />answer2</label
            >

            <label
            ><input
                    name="question1"
                    value=3
                    type="radio"
                    class="input-radio"
            />answer3</label
            >
        </div>
        <!--question2-->
        <div class="form-group">
            <p>
                question 2
            </p>

            <label
            ><input
                    name="question2"
                    value=1
                    type="checkbox"
                    class="input-checkbox"
            />answer1</label
            >
            <label
            ><input
                    name="question2"
                    value=2
                    type="checkbox"
                    class="input-checkbox"
            />answer2</label
            >
            <label
            ><input
                    name="question2"
                    value=3
                    type="checkbox"
                    class="input-checkbox"
            />answer3</label
            >
            <label
            ><input
                    name="question2"
                    value=4
                    type="checkbox"
                    class="input-checkbox"
            />answer4</label
            >
            <label
            ><input
                    name="question2"
                    value=5
                    type="checkbox"
                    class="input-checkbox"
            />answer5</label
            >

        </div>

        <div class="form-group">
            <p>Any comments or suggestions?</p>
            <textarea
                    class="input-textarea"
                    name="content"
                    placeholder="Enter your comment here..."
            ></textarea>
        </div>

        <div class="form-group">
            <button type="submit" id="btnSubmit" class="submit-button">
                Submit
            </button>
        </div>
    </form>
</div>



</body>

 

2.controller

submit을 눌렀을 때 보여주는 화면을 만들어준다.

//submit 등록화면
@PostMapping("/list")
public ModelAndView register(Model model, SurveyVO surveyVO) throws Exception {
    service.register(surveyVO);
    model.addAttribute("msg","등록이 완료되었습니다.");
    ModelAndView view = new ModelAndView();
    view.setViewName("views/surveySuccess");
 return view;
}

경로를 views디렉토리파일의 surveySuccess로 해주었다.

 

survey success html 부분

<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h2 th:text="${msg}"></h2>

<a href="survey.html" th:href="@{list}">목록</a>

</body>
</html>

목록을 클릭하면 /list화면으로 간다.

 

3.service

controller에 register메소드를 만들어줬는데, service에서 더 정확히 정의해준다.

서베이객체를 가지고 있는 register메소드를 만들어줌 , mapper의 create메소드를 사용한다.

@Service
@AllArgsConstructor
public class SurveyService {
   
        private final SurveyMapper mapper;

        public List<SurveyVO> getList() throws Exception {
            return mapper.getList();
        }

        public void register(SurveyVO surveyVO) throws Exception {
            mapper.create(surveyVO);
        }

}

 

4.mapper

mapper부분에서 이제 자바코드를 db에 본격적으로 전달하는 로직이 시작된다.

@Mapper
public interface SurveyMapper {

        
        public List<SurveyVO> getList() throws Exception;

        public void create(SurveyVO surveyVO) throws Exception;

}

자 이제 서베이 객체를 가지고 있는 create라는 메소드를 만들었으니 , db에서 create가 사용되면 객체를 저장하는 쿼리를 작성해보자

 

5.surveyMapper.xml

<insert id="create">
    INSERT INTO survey (writerName, email, question1,question2, content)
        VALUES( #{writerName}, #{email},#{question1}, #{question2} , #{content})
</insert>

db에서는 insert를 이용하면 값이 저장이 되는데 이걸 mapper.xml에 똑같은 쿼리 형태로 db에 저장하는 부분을 만들어준다. create 메소드를 쓰면 , insert로 db에 저장이되며, values에 있는 값은 html에서 name에 있는 것과 동일한 철자로 써줘야 저장된다.

 

6.surveyApiController

데이터를 보여주는 컨트롤러 

content email list를 보여주는걸 만들어보았다.


@RestController
@AllArgsConstructor
public class SurveyApiController {
   private final SurveyService service;
    /*
     @allargsconstructor 가 없으면
     public SurveyApiController(Surveyservice service)
     이렇게 필드값에 각각 파라메터 값을 줘서 만들어야한다
     안만들면 service값이 null로 됨
      */
   @GetMapping("/api/survey/list")
    public SurveyVO getList(){
       try{
           List<SurveyVO> list = service.getList();
           return list.get(0);

       }catch(Exception e){
           e.printStackTrace();
       }
       return null;
   }
   @GetMapping("api/survey/content")
    public String getContent(@RequestParam Integer id){
       try{
           List<SurveyVO> list = service.getList();
           return list.get(id).getContent();
       }catch(Exception e){
           e.printStackTrace();
       }
       return null;
   }
   @GetMapping("api/survey/email/{id}")
    public String getEmail(@PathVariable Integer id){
       try{
           List<SurveyVO> list = service.getList();
           return list.get(id).getEmail();
       }catch(Exception e){
           e.printStackTrace();
       }
       return null;
   }
}