(Udacity) Lesson 4: Spring MVC and Thymeleaf

치즈말랑이·2021년 10월 9일
0
post-thumbnail

퀴즈

1. 템플레이팅으로 재사용할 수 있는 html 구조를 서버데이터에 저장할 수 있는 방법을 생각해보시오. 우리 스스로 이런 html 구조를 만드는 것에 비해 이런 접근법은 어떤 장점이 있는가?

1) HTML을 만드는것은 어렵다.
2) 템플릿은 Spring의 @Controller를 만들수 있게 한다.
3) 템플릿이 더 안전하다.
4) 많은 레이아웃과 시각적 요소들을 재사용할 수 있게 한다.

2. 웹서버, 스프링 컨트롤러, html 템플릿들의 관계를 가장 잘 설명한것

답: 웹서버가 http 요청을 받고 스프링 컨트롤러에서 메소드를 호출한다. 스프링 컨트롤러는 모델 오브젝트를 채우고 뷰 id를 가진 문자열을 반환한다. 뷰 id에 해당하는 템플릿은 모델 오브젝트의 데이터로 채워진다.

3. 서버, 템플릿, MVC에 대해서 옳은것?

1) 컨트롤러는 템플릿과 데이터를 연결한다.
2) 웹 서버는 사용자가 사용할 수 있는 데이터와 액션을 정의한다.
3) 유저 데이터는 요청 URL안에 인코딩 되거나 요청 메세지의 body로 보내질 수 있다.
4) 컨트롤러 메소드는 모델 오브젝트를 반환하고 웹서버는 템플릿을 선택하는데에 이것을 사용한다.

4. 유효한 디자인 패턴들이지만 전부 스프링에서 사용되지는 않는다. 스프링에서 MVC로의 접근을 설명한 것을 찾으시오.

1) 모델 데이터는 발견가능하고 이용자는 바뀐 이벤트에 대한 업데이트를 받는다.
2) 모든 유저 액션과 뷰 업데이트는 http 요청과 응답 오브젝트로 바뀐다. 컨트롤러는 템플릿을 고르고 모델데이터를 저장한다.
3) 한 구성 요소는 데이터를 검색하여 처리하고, 다른 구성 요소는 시각적 표시 데이터를 포맷하며, 컨트롤러는 처음 두 구성 요소 사이의 흐름을 처리한다. ->
4) 컨트롤러는 모델과 뷰의 마스터이다. 모든 상호 작용은 컨트롤러에 의해 정의되며, 컨트롤러는 모델을 업데이트하고 필요에 따라 보기를 반환한다. -> API 기반 MVC폼

5. MVC를 사용하는 시나리오를 찾으시오

1) 브라우저는 웹서버와 커뮤니케이션 하고, 웹서버는 데이터베이스에 정보를 업데이트하고 브라우저로 응답을 반환한다.
2) OS는 사용자들에게 파일 시스템 컨텐츠를 보여주기 위해 파일 익스플로러를 사용한다.
3) 모바일게임은 게임서버와 커뮤니케이션 하기 위해 터치스크린 인터페이스를 제공하고, 게임서버는 게임상태를 서버에 있는 메모리에 업데이트한다.
4) 핸드폰 시스템은 자동메뉴를 통해 신용카드 지불을 하게 한다.
5) 종업원은 고객의 주문을 받고 주방에 전달한다. 음식이 준비되면 고객에게 가져다준다.

6. 만약 당신의 모델 객체가 superGreatString 속성을 가지고 있다면, 당신은 페이지의 텍스트를 superGreatString 값으로 대체하기 위해 당신의 HTML에 어떤 속성을 추가할 수 있는가?

<body>
    <p>Welcome to the future!</p>
</body>

답:
p th:text=”${superGreatString}”

7. 유효하지 않은 Thymeleaf annotation을 가지고 있는 HTML을 고르시오

1)

    <tr th:each="cat : ${cats}">
        <td th:text="${cat.color}" />
        <td th:text="${cat.maxSpeedMph}" />
    </tr>

2)

th:text=”${cat.name} + ‘ is ‘ + {cat.color}”

정답은 아래와 같다.

th:text=”${cat.name + ‘ is ‘ + cat.color}”

3)

th:if="${cat.maxSpeedMph > 10}">Pretty fast
th:elseif="${cat.maxSpeedMph <= 10"> Not as fast

Thymeleaf에서는 elseif가 없고 unless나 switch 등을 사용해야 한다.
4)

<form action="#" th:action="@{'/cat'}" th:object="${cat}" method="POST">
    <label for="newCatText">Name your cat: </label>
    <input type="text" id="newCatName" name="newCatName" th:field="*{name}">
    <input type="submit">
</form>

8. HTML 구문을 th 구문으로 바꾸기

<body>
   <form action="#">
       <input type="submit" value="Visit me">
   </form>
   <h1>Hello, homepage!</h1>
   <h1>Welcome back!</h1>
</body>
<body>
   <form action="#" th:action="@{'/simplehome'}" method="POST">
       <input type="submit" value="Visit me">
   </form>
   <h1 th:if="${firstVisit}">Hello, homepage!</h1>
   <h1 th:unless="${firstVisit}">Welcome back!</h1>
</body>

th:action은 endpoint 지정
POST 메소드 지정

  1. function과 attribute/annotation과의 관계 연결
    1) 사용자 데이터를 수집하는 양식 식별 - th:field
    2) 양식 데이터를 포함한 오브젝트 식별 - @ModelAttirbute
    3) 양식 제출시 호출할 endpoint 식별 - th:action
    4) 지정된 컨트롤러의 경로 식별 - @RequestMapping

9. 다음 구문을 보고 페이지에 처음 방문해서 "Terry"를 입력한 후 버튼을 눌렀을 때 나타나는 반응은?

<body>
<form action="#" th:action="@{'/home'}" th:object="${messageForm}" method="GET">
   <label for="highFiveText">Send a high five to someone: </label>
   <input type="text" id="highFiveText" name="highFiveText" th:field="*{text}">
   <input type="submit">
</form>
<h1 th:each="msg : ${greetings}" th:text="${msg}" th:unless="${msg.contains('Goodbye')}">Hello, homepage!</h1>
</body>
@RequestMapping("/home")
public class HomeController {
   private MessageListService messageListService;

   public HomeController(MessageListService messageListService) {
       this.messageListService = messageListService;
   }

   @GetMapping()
   public String lowFive(MessageForm messageForm, Model model) {
       messageListService.addMessage("low five.");
       model.addAttribute("greetings", messageListService.getMessages());
       return "home";
   }

   @PostMapping()
   public String highFive(MessageForm messageForm, Model model) {
       messageListService.addMessage("high five, " + messageForm.getText() + "!");
       model.addAttribute("greetings", messageListService.getMessages());
       return "home";
   }
}

답: 처음 페이지를 로딩했을 때 low five를 보여주고, 버튼을 눌렀을때 low five를 두번 보여준다.
GET 메소드이기때문에 GetMapping으로 들어가고, GetMapping과 PostMapping 메소드는 같은 data model을 이용한다.

10. 다음 HTML구문을 list가 5개 이하일때만 첫번째 h1을 보여주고, 그거보다 많으면 두번째 h1을 보여주게 바꿔보아라.

<body>
   <form action="#">
       <label for="animalText">Enter an Animal: </label>
       <input type="text" id="animalText" name="animalText">
       <label for="adjective">Enter an Adjective:</label>
       <input type="text" id="adjective" name="adjective">
       <input type="submit">
   </form>
   <h1>Hello, homepage!</h1>
   <h1>I think that's enough!</h1>
</body>
  1. Add an action to the form that directs it to the endpoint /animal using a POST request type and binds the form data to an object called messageForm.
  2. Bind the input text to two fields called animalName and adjective.
  3. Display the contents of the list greetings in the first h1 element. You should display all the elements in the list.
  4. Use conditional logic to only show the list of greetings if there are 5 or fewer messages. Otherwise, show the message ‘I think that’s enough!’
<body>
<form action="#" th:action="@{'/animal'}" th:object="${messageForm}" method="POST">
   <label for="animalText">Enter an Animal: </label>
   <input type="text" id="animalText" name="animalText" th:field="*{animalName}">
   <label for="adjective">Enter an Adjective:</label>
   <input type="text" id="adjective" name="adjective" th:field="*{adjective}">
   <input type="submit">
</form>
   <h1 th:unless="${#lists.size(greetings) > 5}" th:each="msg : ${greetings}" th:text="${msg}">Hello, homepage!</h1>
   <h1 th:if="${#lists.size(greetings) > 5}">I think that's enough!</h1>
</body>

11. 어떤것이 파일 업로드 요청을 받기위한 메소드인가?

1)

@PostMapping
public String uploadFile(@RequestParam MultiPartFile file, Model model)

2)

@PostMapping
public String uploadFile(@ModelAttribute FileUploadForm fileuploadForm, Model model)

3)

@GetMapping
public String uploadFile(@RequestParam File file, Model model)

4)

@PostMapping
public String uploadFile(@RequestParam InputStream fileStream, Model model)

5)

@PostMapping
public String uploadFile(@ModelAttribute String filePath, Model model)

12. 틀린것을 고르시오.

1) Spring MVC는 대용량 파일을 업로드하기에 효율적인 방법은 없다.
2) Spring MVC는 브라우저 쿠키 데이터를 보내는데에 효율적인 방법은 없다.
3) Spring MVC 컨트롤러 메소드에서 HTTP 요청 헤더를 추출하는데 효율적인 방법은 없다.
4) Spring MVC 컨트롤러 메소드에서 URL 경로 segent를 변수로 추출하는 효율적인 방법은 없다.

대용량 : MultiPartFile

profile
공부일기

0개의 댓글

관련 채용 정보