교육 (Today I Learned)/Hanaro

[Hanaro] 49일차 / Spring Boot (Thymeleaf, 데이터 전달 및 Param 값 받기, List로 데이터 저장)

Bay Im 2024. 3. 27. 00:30

Thymeleaf

  • 타임리프의 조건식
    • th:if
      • if 조건이 false인 경우 해당 값이 랜더링되지 않는다.
      • 예시
        • <p th:if="${ role } == 'admin'" th:text="|사용자는 관리자입니다.|"></p>
    • th:unless
      • unless 조건이 false인 경우 값이 출력된다.
      • 예시
        • <p th:unless="${ role } == 'admin'" th:text="|사용자는 관리자가 아님.|"></p>
    • th:switch
      • 예시
        • <div th:switch="${ role }">
              <p th:case="'admin'">사용자는 관리자입니다.</p>
              <p th:case="'guest'">사용자는 손님입니다.</p>
              <p th:case="*">사용자는 그외 권한입니다.</p>
          </div>
  • th:block
    • 타임리프의 자체 로직을 위한 블록 태그
    • 위의 조건식과 함께 사용한다.
    • 예시
      • <th:block th:if="${ address_null == null }">
            <p>address_null은 null입니다.</p>
        </th:block>
        
        <th:block th:unless="${ address_null == null }">
            <p>address_null은 null이 아닙니다.</p>
        </th:block>
  • 타임리프의 날짜/금액 출력
    • 날짜
      • 컨트롤러에서 model.addAttribute("localDate", LocalDate.*now*());
      • html에서 <p th:text="${ #temporals.format(localDate, 'yyyy/MM/dd') }"></p>
    • 금액
      • 컨트롤러에서 model.addAttribute("number1", 12345678);
      • html에서 <p th:text="|${ #numbers.formatInteger(number1, 3, 'COMMA') }원|"></p>
  • th:object
    • 객체를 선택한다.
    • 블록 안에서 객체 선택후 *{ 변수 } 로 해당 객체(클래스)의 변수에 접근한다.
    • 예시
      • <th:block th:object="${ member }">
            <p th:text="*{ username }"></p>
            <p th:text="*{ password }"></p>
        </th:block>
  • th:each
    • 객체 리스트 출력
    • 예시
      • <table border="1">
            <tr th:each="member, status : ${ list }">
                <td><span th:text="${ status.count }"></span></td>
                <td><span th:text="${ member.username }"></span></td>
                <td><span th:text="${ member.password }"></span></td>
            </tr>
        </table>
  • th:href
    • 내부 링크로 이동
    • 태그 안에 th:href=”@{ 이동할html명 }” 작성
    • 예시
      • <a th:href="@{ index7 }">타임리프 링크입니다. index7로 redirect 됩니다.</a>

 

 

데이터 전달 및 Param 값 받기

  • UI 템플릿으로 데이터 전달 방법 4가지 (타임리프, JSP, 머스테치)
    • request 객체, session 객체
    • GET, POST 파라미터
      •   	@RequestMapping("/model2")
            public String model2(HttpServletRequest request){
                String param_name = request.getParameter("name");
                String param_age = request.getParameter("age");
                request.setAttribute("name", param_name);
                request.setAttribute("age", param_age);
        
                return "index";
             }
    • Model 객체
    • ModelAndView 객체
      • 모델(데이터)와 뷰(HTML)을 동시에 저장 및 응답하는 객체
      • 예시
        • 	 @RequestMapping("model4") 
              public ModelAndView model3(HttpServletRequest request, ModelAndView mv) {
                  mv.addObject("name", "춘향이");
                  mv.addObject("age", "18");
          
                  //뷰 설정
                  mv.setViewName("index"); 
          
                  return mv;
              }
  • 내장 객체별 수명 주기
    • application
      • 웹 브라우저를 닫을 때까지
    • session
      • 로그아웃하기 까지
    • request
      • 요청에 대한 응답하기 까지
    • model
      • request와 동일
  • @RequestMapping
    • 호출 경로를 매개변수로 받을 수 있다.
    • GET, POST, PUT, PATCH, DELETE 모두 받을 수 있다.
    • request 객체는 HTTP 요청에 대한 정보를 담고있다.
      • request.getSession().setAttribute("isLogin", "true");
    • 예시
      •  	 // URL : localhost:8080/loginAction1/hong/1234
        		@RequestMapping("loginAction1/{username}/{password}")
            public String loginAction1( @PathVariable("username") String username,
                                        @PathVariable("password") String password,
                                        Model model, Member member){
                model.addAttribute("username", username);
                model.addAttribute("password", password);
                return "loginResult";
            }
  • required
    • required = true
      • Nonnull이 기본값 (null이면 오류)
    • required = false
      • 매개변수로 null 허용
      • 예시 (@RequestParam 매개변수에 사용)
        • @RequestParam(value="username", **required = false**, defaultValue = "김진사") String username, …
  • defaultValue
    • 매개변수의 값이 없을 때 기본값 지정
    • 예시
      • @RequestParam(defaultValue = "홍길동")
  • Param 값 받는 4가지 방법
    • 먼저 html에서 submit으로 사용자에게 입력값 받기
      • 예시
      • <form action="이동할url명" method="post">
            <input type="text" name="username" > <br>
            <input type="password" name="password" > <br>
            <input type="submit" value="로그인">
        </form>
    • request.getParameter() 사용
      1. 메서드의 매개변수는 HTTPServletRequest request, Model model, 클래스명 변수명을 받는다.
      2. 변수 선언 후 html에서 값을 받았던 name을 request.getParameter(”name”) 형태로 받아온다.
      3. 해당 변수를 model.addAttribute(”attributeName”, 변수명) 형태로 추가한다.
      • 예시
        •   	@RequestMapping("loginAction1")
            	// 1. 메서드의 매개변수는 HTTPServletRequest request, Model model, 클래스명 변수명을 받는다. 
               public String loginAction1(HttpServletRequest request,
                                         Model model, Member member) {
                  // 2. 변수 선언 후 html에서 값을 받았던 name을 request.getParameter(”name”) 형태로 받아온다. 
                  String username = request.getParameter("username");
                  String password = request.getParameter("password");
                  
                  // 3. 해당 변수를 model.addAttribute(”attributeName”, 변수명) 형태로 추가한다. 
                  model.addAttribute("username", username);
                  model.addAttribute("password", password);
          
                  return "loginResult";
              }
    • @PathVariable 사용
      1. 메서드의 매개변수에서 @PathVariable(”html에서받았던name”) 데이터타입 변수명 형태로 준다.
      2. 매개변수는 위의 @PathVariable, Model model, 클래스명 변수명을 받는다.
      3. 해당 매개변수명을 model.addAttribute(”attributeName”, 매개변수명) 형태로 추가한다.
      • 예시
        • @RequestMapping("loginAction1/{username}/{password}")
          // 1. 메서드의 매개변수에서 @PathVariable(”html에서받았던name”) 데이터타입 변수명 형태로 준다.
          // 2. 매개변수는 위의 @PathVariable, Model model, 클래스명 변수명을 받는다.
              public String loginAction1( @PathVariable("username") String username,
                                          @PathVariable("password") String password,
                                          Model model, Member member) {
                                          
          				// 3. 해당 매개변수명을 model.addAttribute(”attributeName”, 매개변수명) 형태로 추가한다. 
                  model.addAttribute("username", username);
                  model.addAttribute("password", password);
                  
                  return "loginResult";
              }
    • @RequestParam 사용
      1. 메서드의 매개변수에서 @RequestParam(”html에서받았던name”)와 Model model을 받는다.
      2. RequestParam은 required로 null 여부와 defaultValue로 기본값을 설정할 수 있다.
      3. 위에서 추가한 매개변수명 model.addAttribute(”attributeName”, 매개변수명) 형태로 추가한다.
      • 예시
        • @RequestMapping("loginAction2")
          // 1. 메서드의 매개변수에서 @RequestParam(”html에서받았던name”)와 Model model을 받는다. 
          // 2. RequestParam은 required로 null 여부와 defaultValue로 기본값을 설정할 수 있다. 
              public String loginAction2(
                      @RequestParam(value="username",
                              required = false, defaultValue = "김진사") String username,
                      @RequestParam("password") String password,
                      Model model){
                  
                  // 3. 위에서 추가한 매개변수명 model.addAttribute(”attributeName”, 매개변수명) 형태로 추가한다.
                  model.addAttribute("username", username);
                  model.addAttribute("password", password);
                  
                  return "loginResult";
              }
    • Map 사용
      1. @RequestParam으로 Map을 선언하고, Model model을 매개변수로 받는다.
      2. 선언한 map을 model.addAttribute로 추가한다.
      • 예시
        •     @RequestMapping("loginAction4")
              // 1. @RequestParam으로 Map을 선언하고, Model model을 매개변수로 받는다.
              public String loginAction5(
                      @RequestParam Map<String, Object> map,
                      Model model){
          				
          				// 2. 선언한 map을 model.addAttribute로 추가한다.
                  model.addAttribute("map", map);
          
                  return "loginResult3";
              }
  • ArrayList 사용하여 데이터 저장
    1. ArrayList 선언
    2. 메서드 안에 클래스객체 new 인스턴스로 생성한다.
    3. 해당 클래스객체.setter변수(매개변수명); 형태로 클래스객체에 값을 넣는다.
    4. 이후 List에 클래스 객체 전체를 add 한다.
    • 예시
      •   	// 1. ArrayList 선언
            List<Member> memberList = new ArrayList<>();
        
        		@PostMapping("join")
            public String join(@RequestParam(defaultValue = "홍길동", required = false) String inputName,
                               @RequestParam String inputEmail,
                               @RequestParam String inputPw,
                               @RequestParam String inputPw2,
                               Model model){
                // 2. 메서드 안에 클래스객체 new 인스턴스로 생성한다.
                Member member = new Member();
                
                // 3. 해당 클래스객체.setter변수(매개변수명); 형태로 클래스객체에 값을 넣는다.
                member.setName(inputName);
                member.setEmail(inputEmail);
                member.setPassword(inputPw);
        
        				// 4. 이후 List에 클래스 객체 전체를 add 한다. 
                memberList.add(member);
                
                return "index";
            }