7.springBoot/1)개념_springBoot

springBoot_개념_Day_10

구이제이 2024. 4. 8. 17:41

1. member.html

2. member.html

3. MemberControllerTest

4. MemberControllerTest



5.부트스트랩 활용

6.레이아웃 이용

7.관계 설정(매핑)

8. 자습





ㅡㅡㅡ

 

●1.

●2.

<!DOCTYPE html>

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

     xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"

     layout:decorate="~{layouts/layout}"> <!-- 추가 -->

>

<!--<head>-->

<!--    <meta charset="UTF-8">-->

<!--    <meta name="viewport" content="width=device-width, initial-scale=1.0">-->

<!--    <title>회원가입</title>-->

 <style>

     p.fieldError{

         color: red;

     }

     div.content{

         width: 500px/*  width:50%; */

         margin: 0 auto;

         margin-top: 50px; /* margin-top : 23.5% */

     }

     div.content>h2{

         text-align: center;

     }

     div.btn-style{

         text-align: center;

     }

 </style>

  <script>

      //회원가입시 실패하면 에러 메시지 경고창 보여주기

      $(document).ready(function(){

          let errorMessage = [[${errorMessage}]];

          if(errorMessage != null){

              alert(errorMessage);

          }

      });

 

  </script>

<!--</head>

<body>-->

 

 <div layout:fragment="content" class="content"> <!-- 레이아웃처리 -->

         <h2>회원 가입</h2>

           <form action="/members/new" role="form" method="post"  th:object="${memberDto}">

                 <div class="form-group">

                     <label th:for="userid">아이디</label>

                     <input type="text" th:field="*{userid}" class="form-control" placeholder="아이디를 입력해주세요">

                     <p th:if="${#fields.hasErrors('userid')}" th:errors="*{userid}" class="fieldError">입력 오류</p>

                 </div>

             <div class="form-group">

                 <label th:for="name">이름</label>

                 <input type="text" th:field="*{name}" class="form-control" placeholder="이름을 입력">

                 <p th:if="${#fields.hasErrors('name')}" th:errors="*{name}" class="fieldError">입력 오류</p>

             </div>

             <div class="form-group">

                 <label th:for="password">비밀번호</label>

                 <input type="password" th:field="*{password}" class="form-control" placeholder="비밀번호 입력">

                 <p th:if="${#fields.hasErrors('password')}" th:errors="*{password}" class="fieldError">입력 오류</p>

             </div>

             <div class="form-group">

                 <label th:for="email">이메일주소</label>

                 <input type="email" th:field="*{email}" class="form-control" placeholder="이메일을 입력">

                 <p th:if="${#fields.hasErrors('email')}" th:errors="*{email}" class="fieldError">입력 오류</p>

             </div>

 

             <div class="form-group">

                 <label th:for="address">주소</label>

                 <input type="text" th:field="*{address}" class="form-control" placeholder="주소를 입력">

                 <p th:if="${#fields.hasErrors('address')}" th:errors="*{address}" class="fieldError">입력 오류</p>

             </div>

             <div class="btn-style">

                 <button type="submit" class="btn btn-primary" >Submit</button>

             </div>

             <!-- spring security 이용 -->

             <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">

         </form>

     </div>

 </div>

</body>

</html>

 

 




●3.

●4.

 

package com.cshop.controller;

 

import com.cshop.dto.MemberDto;

import com.cshop.entity.Member;

import com.cshop.service.MemberService;

import org.junit.jupiter.api.DisplayName;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.security.crypto.password.PasswordEncoder;

import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers;

import org.springframework.test.context.TestPropertySource;

import org.springframework.test.web.servlet.MockMvc;

import org.springframework.transaction.annotation.Transactional;

 

import static org.junit.jupiter.api.Assertions.*;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;

 

//테스트 관련해서 찾아봐야합니다. junit테스트, 스프링부트테스트 라고 검색

// 다 만들고, 테스트

//실제, 1.단위테스트가 문제가 없어야,

//2.통합테스트, 그리고 3.시스템테스트 해야합니다.

//crud에 대한 테스트,

//JPA, Mybatis 선택

 

 

 

 

// mock mvc컨트롤러로 실제 존재하지 않지만,

// 가짜 객체 만들어주는 '목 mvc'

// 요청하는 것처럼 데스팅 할수 있다.

 

@SpringBootTest

@AutoConfigureMockMvc //MockMvc 테스트를 위해 이 어노테이션을 선언

@Transactional     //import org.springframework.transaction.annotation.Transactional; 이거 넣어줘야합니다.

@TestPropertySource(locations = "classpath:application-test.properties")

class MemberControllerTest {

 

   @Autowired

   private MemberService memberService;

 

   @Autowired

   private MockMvc mockMvc; //실제 객체와 비슷하지만 테스트에 필요한 기능만 가지는 가짜 객체

   //import org.springframework.test.web.servlet.MockMvc; 이거 선택

 

   @Autowired

   PasswordEncoder passwordEncoder;

 

   //멤버 객체를 생성

   public Member createMember(String userid, String password){

       MemberDto memberDto = new MemberDto();

       memberDto.setUserid(userid);

       memberDto.setName("홍길동");

       memberDto.setPassword(password);

       memberDto.setEmail("a@a.com");

       memberDto.setAddress("서울시 강남구 역삼동");

 

       Member member = Member.createMember(memberDto, passwordEncoder);

       return memberService.saveMember(member);

   }

 

 

   @Test

   @DisplayName("로그인 성공 테스트")

   public void loginSuccessTest() throws Exception {

       String userid = "a1234";

       String password = "a123456789";

       this.createMember(userid, password);

 

       //perform() : MockMvc를 사용해서 HTTP요청

       //formLogin() : form의 Login

       //andExpect() : 요청하고 받은 응답 본문의 내용이 기대하고 있는 것인지 확인

 

       //formLogin() 은 import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; 이거 임폴트

       mockMvc.perform(formLogin().userParameter("userid")

               .loginProcessingUrl("/members/login")

               .user(userid).password(password))

               .andExpect(SecurityMockMvcResultMatchers.authenticated());

 

//                .andExpect(Model().attribute("aa","기대값"));

//                .andExpect(status().isOk());

 

   }

 

   @Test

   @DisplayName("로그인 실패 테스트")

   public void loginFailTest() throws Exception {

       String userid = "a1234";

       String password = "126789";

       this.createMember(userid, password); //만든 패스워드 1)

 

       //formLogin() 은 import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin; 이거 임폴트

       mockMvc.perform(formLogin().userParameter("userid")

                       .loginProcessingUrl("/members/login")

                       .user(userid).password("1234")) //입력한 패스워드 2)  , 1과2의 불일치

              // .andExpect(SecurityMockMvcResultMatchers.authenticated());

               .andExpect(SecurityMockMvcResultMatchers.unauthenticated());

   }

}





●5.

 



#fragments




#layouts






●6

 

디펜던시 추가

 

 

 





●관계 설정(매핑)

 

 

연관 관계 매핑

1. 관계수의 종류 :

       일대일(1:1)의 관계 = @OneToOne ex) 고객과장바구니

       일대다(1:N)의 관계 = @OneToMany

       다대일(N:1)의 관계 = @ManyToOne

       다대다(N:M)의 관계 = @ManyToMany

 

2. 관계의 방향성

   관계성 모델 : 양방향

   객체 모델 : 단방향, 단방향*2 -> 양방향