티스토리 뷰

프로그래밍/Web

Spring MVC 맛보기

국윤창 2018. 1. 21. 19:30

이해하기 위해 간단한 사람 이름, 나이 적는 프로그램을 만들어 어떻게 돌아가는지 살펴보자.


1. Person 객체 만들기

테스트하기 위한 객체이다. 앞서 소개한 POJO 객체라는데 그냥 순수 Java 객체라고 생각하면 되겠다..

그림 1과 같은 디렉토리에 Person.java를 만들고 코드를 작성하자.


Person 객체 생성[그림 1] Person 객체 및 위치


2. PersonController, 뷰 만들기

테스트를 위해 Controller와 뷰를 만들어야한다.

Person.java를 생성한 위치에 PersonController.java를 만들자. 그리고 아래와 같은 코드를 작성하자.

package com.example.demo;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@EnableAutoConfiguration
public class PersonController {
    @RequestMapping(value="/person", method=RequestMethod.GET)
    public String newPerson(Model model)
    {
        model.addAttribute("person", new Person());

        return "new";
    }

    @RequestMapping(value="/person", method=RequestMethod.POST)
    public String submitPerson(@ModelAttribute Person person, Model model)
    {
        model.addAttribute("person", person);

        return "result";
    }
}

위 코드에서 @로 나타낸 것은 annotation이라 부른다. 

나중에 자세히 포스트하겠지만 간단히 보자면, 클래스에 annotation으로 @Controller를 붙이면 스프링이 패키지를 스캔할 때 이 클래스를 Controller Bean으로 인식한다. 그리고 @RequestMapping은 요청 URL을 어떤 함수가 처리할 지 결정할 수 있도록 하고 HTTP 전송 방식을 결정할 수 있도록 해준다. 예를들어 위의 newPerson 함수는 http://localhost:8080/person에 GET 방식으로 접속했을 때 호출된다.


RequestMapping으로 호출된 함수가 model.addAttribute함수를 이용해 문자열과 객체를 매개변수로 넘기는 것을 볼 수 있다. 이것은 thymeleaf에서 오브젝트를 해당 이름으로 사용할 수 있게 해준다.


마지막으로 함수가 문자열을 반환하는데 아래 그림 2 경로에서 일치하는 html파일을 찾아서 가져오도록 한다. 이런 방식에는 여러가지가 있는데 참고의 링크에 자세히 나온다.


이제 Person 정보를 입력하기 위한 Form 화면이 필요하므로 new.html파일을 그림 2와 같은 위치에 만들고 코드를 작성한다.

resources->templates->new.html[그림 2] new.html 위치


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>New Person</title>
</head>

<body>
    <h1>New Person</h1>

    <!--/*@thymesVar id="person" type="com.example.demo.Person"*/-->
    <!--/*@thymesVar id="name" type="String"*/-->
    <!--/*@thymesVar id="age" type="int"*/-->
    <form action="#" th:action="@{/persons}" th:object="${person}" method="post">
        <p>title: <input type="text" th:field="*{name}"/></p>
        <p>age: <input type="text" th:field="*{age}"/></p>
        <p><input type="submit" value="Submit"/><input type="reset" value="Reset"/></p>
    </form>
</body>
</html>

xmlns를 이용해 네임스페이스를 지정하자. thymeleaf의 네임스페이스를 지정하고 form에서 사용하는 것을 보면 xmlns로 지정한 것을 접두사로 붙이는 것을 알 수 있다.


자세히 공부해야겠지만 먼저 간단히 보자면, 링크 URL을 표현할 때는 @{...}를 사용한다. 변수를 표현할 때는 ${...}를 사용한다. *{...}같은 경우 th:object가 지정돼있지 않으면 ${...}와 똑같다. 하지만 지정돼있으면 th:object로 지정된 object의 멤버를 나타낸다. (예를들면 *{name}은 person.name이다.)


form 태그 위에 특이한 주석이 있는데, IntelliJ에서 model로 넘겨준 thymeleaf 내 변수(예를들면 ${person})를 인식하지 못하는 문제때문에 넣은 것이다.


이 문제는 IntelliJ에서 spring boot와 thymeleaf를 같이 사용할 때 나타나는 문제이며 위 주석을 사용하여 인식되게 할 수 있다.


방식은 그냥 변수의 경우 <!--@thymesVar id="이름" type="패키지.주소.클래스이름"--> 로 인식하게 하며, 

*{name}과 같은 멤버 변수의 경우 <!--@thymesVar id="이름" type="데이터타입(String, int 등)"--> 로 인식하게 한다.


맛만 보려고 했는데 안돼서 한참 찾아봤다. 졸라 불맛이었다.


이제 Person 정보를 입력한 뒤 제대로 입력됐는지 확인하기 위한 result.html을 작성하자.


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>Result</title>
</head>

<body>
    <h1>Result</h1>
    <!--/*@thymesVar id="person" type="com.example.demo.Person"*/-->
    <p th:text="'name: ' + ${person.name}"/>
    <p th:text="'age: ' + ${person.age}"/>
</body>
</html>


3. 빌드 및 실행


이제 빌드를 해보자. Build->Build Project를 해보고 안되면 File->Project Structure에서 아래 그림 3처럼 jdk가 설정돼있는지 확인하자.


jdk설정 확인[그림 3] jdk 설정. 현재는 1.8 버전으로 돼있다.


빌드가 끝났으면 Run->Run '어플리케이션 이름'을 해서 실행해보자.


실행한 후 브라우저에서 localhost:8080/person 으로 접속해보자. (참고로 8080은 포트번호이다. application.properties에 server.port=포트번호를 입력 및 저장해서 바꿀 수있다.)


아래와 같은 화면이 나오면 성공이다.


성공 화면[그림 4] 성공 화면


이름과 나이를 입력 후 Submit 버튼을 누르자.


버튼을 누른 후 아래 그림 5 화면이 나오면 결과창도 성공이다.


결과 화면[그림 5] 결과 화면


다음엔 thymeleaf 문법과 annotation에 대해서 공부를 해야겠다.


* 참고

MVC 예제 코드: http://javasampleapproach.com/spring-framework/spring-mvc/spring-web-mvc-form-submission-spring-boot


RequestMapping 관련: http://cranix.net/337

http://yang1650.tistory.com/133


thymeleaf 표현식: http://cyberx.tistory.com/132


thymeleaf 변수 인식 에러: https://questionfocus.com/spring-boot-thymeleaf-in-intellij-cannot-resolve-vars.html

https://youtrack.jetbrains.com/issue/IDEA-132738


HTML Reference(Front-end 쪽 자세히 나와있음. 강의도 있음): https://developer.mozilla.org/en-US/docs/Web/HTML


xmlns: http://blog.daum.net/_blog/BlogTypeView.do?blogid=0GZT6&articleno=13&categoryId=89922&regdt=20130108110048

'프로그래밍 > Web' 카테고리의 다른 글

Annotation과 Bean  (2) 2018.01.27
Spring Bean  (2) 2018.01.27
IntelliJ로 Spring 프로젝트 생성  (0) 2018.01.21
Spring 특징  (0) 2018.01.21
HTTP  (0) 2018.01.21
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함