본문으로 바로가기
반응형


thymeleaf 에서 Spring boot로 구동되는 서버단으로 값을 전달할 때에 다양한 방법이 있을 수 있다.

그 중 생각나는 세가지 방법을 로그인 프로세스 예시를 통해 알아보도록 하자.



1. 전통적인 html form submit


html form 태그로 감싸 포함된 항목들을 get 혹은 post 방식으로 submit하여, 서버의 컨트롤러에서 HttpServletRequest로 받는 방식이다.


<form class="m-t" role="form" action="/login.do" id="loginForm" method="post">
       <div class="form-group">
           <input type="email" name="email" id="email" class="form-control"
  placeholder="Email" required="required"/>
       </div>
       <div class="form-group">
           <input type="password" name="password" id="password" class="form-control" 
placeholder="Password" required="required"/>
       </div>
       <button type="submit" class="btn btn-primary block full-width m-b">Login</button>
   </form>
cs


위와 같이 loginForm이라는 id의 form이 email과 password를 감싸고 있다.

이 form은 submit type의 버튼을 통해 /login.do로 HttpServletRequest에 값을 담아 전달한다.


이제 값을 전달받을 /login.do 컨트롤러를 보자.


1
2
3
4
5
6
7
8
9
    @RequestMapping("/login.do")
    private ModelAndView doLogin(HttpServletRequest request,
 HttpServletResponse response) throws Exception {
        System.out.println("---------------------> login!!!!!!!!!!!");
        System.out.println("---------------------> " + request.getParameter("email"));
        System.out.println("---------------------> " + request.getParameter("password"));
        System.out.println("---------------------> login!!!!!!!!!!!");
        
        return new ModelAndView("main");
    }
cs


HttpServletRequest에 담긴 값들을 .gerParameter() 메소드를 통해 꺼내 쓰기만 하면 된다.

직관적이고 간단한 방법이라 1~2개의 값만을 전달 받아 바로 활용하기에 좋다.




2. thymeleaf 가 제공하는 방법


위 방법은 간단하기는 하지만, 가져온 값을 만약 어떤 객체에 담아야 한다면 값 하나 하나 따로따로 ".setXX()" 를 해 주어야 할 것이다. 항목이 많아지면 많아질수록 번거롭다.

thymeleaf 가 제공하는 custom tag를 사용하여 편하게 값을 가져올 수 있다.(반대로 서버->클라이언트 역시 비슷하다.)


(Thymeleaf를 사용할 때, 서버에서 값을 html로 전달하는 방법 : http://www.leafcats.com/28 )



우선 Login 화면을 호출하는 컨트롤러에서부터 값을 담을 객체를 @ModelAttribute 어노테이션을 붙여 던져준다.

1
2
3
4
    @RequestMapping("/moveLogin.do")
    private ModelAndView moveLogin(@ModelAttribute LoginVO loginVO,
 HttpServletRequest request) throws Exception {
        return new ModelAndView("login/login");
    }
cs


그 다음은 아래와 같이 form 태그의 속성들을 선언해 준다.

1
2
3
4
5
6
7
8
9
   <form class="m-t" role="form" th:action="@{/login.do}" 
th:object="${loginVO}"  action="#" id="loginForm" method="post">
       <div class="form-group">
           <input type="email" th:field="*{email}" name="email" 
id="email" class="form-control" placeholder="Email" required="required"/>
       </div>
       <div class="form-group">
           <input type="password" th:field="*{password}" name="password" 
id="password" class="form-control" placeholder="Password" required="required"/>
       </div>
       <button type="submit" class="btn btn-primary block full-width m-b">Login</button>
   </form>
cs


위 HTML 코드처럼 form 태그의 th:actoion 속성에 전달할 url을, th:object에 값을 담을 객체를 잡아준다.

그 다음으로 각각 값을 입력받을 input 태그의 th:field에 form태그에서 선언한 객체에 담길 항목들을 잡아주면 된다.


마지막으로 submit으로 값을 넘겨받을 컨트롤러를 아래와 같이 코딩하면 loginVO객체 안에 email과 password 값이 각각 들어간다.


1
2
3
4
5
6
7
8
9
10
    @RequestMapping("/login.do")
    private ModelAndView doLogin(@Valid LoginVO loginVO, BindingResult result,
            RedirectAttributes redirect, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("---------------------> login!!!!!!!!!!!");
        System.out.println("---------------------> " + loginVO.getEmail());
        System.out.println("---------------------> " + loginVO.getPassword());
        System.out.println("---------------------> login!!!!!!!!!!!");
        
        return new ModelAndView("main");
    }
cs



이 방법을 사용하면, 별다른 스크립트 작성 없이 JSP가 아닌 순정 HTML에서 객체 통채로 값을 주고 받을 수 있다.

아, thymeleaf의 커스텀 태그를 사용하기 위해서는 반드시 html태그에 아래의 xmlns 속성을 지정해 주어야 한다.


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




3. Ajax 통신


이 방법은 잘 알려진 자바스크립트 코드를 사용하여 서버와 Ajax 통신하여 값을 전달한다.

3번은 다음번 글에 좀 더 자세히 중점적으로 포스팅 하겠다.



반응형

 Other Contents