Sesac 12일차

SungMin·2022년 10월 20일
0

Sesac-Java/Spring

목록 보기
8/13

요청 처리

● PathVariable (깔끔함) - 요청 주소의 경로명 활용
● ModelAttribute (명확함)

  • Model / DTO / VO 등 객체와 연계하여 활용
  • JPA, MyBatis 등 ORM 프레임워크 활용

연습문제

  • 클라이언트의 요청 파라미터에 따라 응답이 달라지도록 작성하기
    -/req/data
    -/req/data?area=제주도
    -/req/data?area=제주도&score=100

  • RequestParam과 Map을 응용하여 해결


package com.example.basic.controller;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestController {
	// 연습문제
    @GetMapping("req/data")
    public Map<String,Object> reqData(@RequestParam Map<String, Object> map) {
        return map;
    }


}

  • 출력 결과물

타임리프(Thymleaf)

HTML Template

  • HtmlController
package com.example.basic.controller;

import java.util.*;
import com.example.basic.model.Member;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HtmlController {
    @RequestMapping("/")
    public String home(){
        return "home";
    }

    @GetMapping("html/string")  // @RequestMapping(method = RequestMethod.GET)과 같은 의미
    public String string(){
        return "html/string"; 
        // 반환(리턴)타입이 String일 때 반환값에 보여줄 경로의 페이지를 명시해준다.
    }

    @GetMapping("html/void")
    public void htmlVoid(){
    }

    @GetMapping("html/map")
    public Map<String,Object> htmlMAp(Map<String,Object> map){
        Map<String,Object> map2 = new HashMap<String,Object>();
        return map2;
    }

    @GetMapping("html/model")
    public Model htmlModel(Model model){
        return model;
    }

    @GetMapping("html/modelAndView")
    public ModelAndView htmlModelAndView(){
        ModelAndView mav = new ModelAndView();
        // ModelAndView를 리턴받을때 setViewName메소드를 통해서 출력할 화면을 지정해줄 수 있다.
        mav.setViewName("html/model_and_view");
        return mav;
    }

    @GetMapping("html/object")
    public Member htmlObject(){
        Member member = new Member();
        member.setName("홍길동");
        return member;
    }

    // 연습문제1
    @GetMapping("html/exam")
    public String htmlexam(){
        return "html/exam";
    }

    @GetMapping("signup")
    public String signup(@ModelAttribute Member member){
        // localhost:8080/signup?name=값1&userId=값2&userPassword=값3
        // Model클래스인 member클래스 안에 있는 변수명으로
        // 파라미터를 받아오고, 지정한 html에 member라는 이름으로 데이터가 전송된다.
        // html에서는 전송받은 member라는 이름으로 데이터를 사용할 수 있다(thymleaf사용).
        return "signUp";
    }

    @GetMapping("welcome")
    public String welcome(Model model){
        ArrayList<String> list = new ArrayList<>();
        list.add("list1");
        list.add("list2");
        list.add("list3");
        model.addAttribute("list", list);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("key1", "value1");
        map.put("key2", 22);
        model.addAttribute("map", map);

        Member member = new Member();
        member.setName("길동");
        member.setUserId("gil");
        member.setUserPassword("gil123");
        model.addAttribute("member", member);

        model.addAttribute("message", "타임리프");
        return "welcome";
    }

}

  • 입력한 소스
<html xmlns:th="http://www.thymeleaf.org">

    <head> 
    </head>       

    <body> 
        <h1>List 정보 확인</h1>
        <h3>[[${list}]]</h3>
        <h3>[[${list[0]}]]</h3>
        <h1>Map 정보 확인</h1>
        <h3>[[${map}]]</h3>
        <h3>[[${map.key1[0]}]]</h3>
        <h3>[[${map['key2']}]]</h3>
        <h1>Member 정보 확인</h1>
        <h3>[[${member}]]</h3>
        <h3>[[${member['userId']}]]</h3>
        <h3>[[${member.userPassword}]]</h3>
        <h1>Message 정보 확인</h1>
        <h3>[[${message}]]</h3>
    </body>

</html>

  • 페이지 소스 보기
<html>

    <head> 
    </head>       

    <body> 
        <h1>List 정보 확인</h1>
        <h3>[list1, list2, list3]</h3>
        <h3>list1</h3>
        <h1>Map 정보 확인</h1>
        <h3>{key1=value1, key2=22}</h3>
        <h3>v</h3>
        <h3>22</h3>
        <h1>Member 정보 확인</h1>
        <h3>Member(name=길동, userId=gil, userPassword=gil123)</h3>
        <h3>gil</h3>
        <h3>gil123</h3>
        <h1>Message 정보 확인</h1>
        <h3>타임리프</h3>
    </body>

</html>

  • 출력 결과물

Variable Expression - ${ ... }

  • 같은 내용의 3가지 표현
<html xmlns:th="http://www.thymeleaf.org">

    <head> 
    </head>       

    <body> 
        <!-- 타임리프 표현하는 방법 3가지-->
        <!-- 1. 열리는 태그와 닫히는 태그 사이에 데이터 출력-->
        <!-- span태그 : 별도의 영역이 없는 태그-->
        아이디:<span>[[${user.userId}]]</span><br/>
        이름:<span>[[${user.userName}]]</span><br/>
        비밀번호:<span>[[${user.userPw}]]</span><br/>
        <hr/>
        <!-- 2. 열리는 태그에 th:속성으로 표현-->
        아이디:<span th:text="${user.userId}"></span><br/>
        이름:<span th:text="${user.userName}"></span><br/>
        비밀번호:<span th:text="${user.userPw}"></span><br/>
        <hr/>
        <!-- 3. 열리는 태그에 data-th-속성명="값"으로 표현-->
        아이디:<span data-th-text="${user.userId}"></span><br/>
        이름:<span data-th-text="${user.userName}"></span><br/>
        비밀번호:<span data-th-text="${user.userPw}"></span><br/>
    </body>

</html>

  • 출력 결과물

Iteration - th:each

package com.example.basic.controller;

import java.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.basic.model.Member;

@Controller
public class ThymleafController {
    @GetMapping("user") // http://localhost:8080/user
    public String user(Model model){
        Map<String,Object> user = new HashMap<String,Object>();
        user.put("userId", 1);
        user.put("userName","user01");
        user.put("userPw","1234");
        model.addAttribute("user", user);
        return "user";
    }

    @GetMapping("userList")
    public String userList(Model model){
        ArrayList<Member> userList = new ArrayList<>();
        //홍길동 유저 생성
        Member member = new Member();
        member.setName("홍길동");
        member.setUserId("hong");
        member.setUserPassword("1");
        userList.add(member);
        // 이순신 유저 생성
        member = new Member();
        member.setName("이순신");
        member.setUserId("lee");
        member.setUserPassword("2");
        userList.add(member);
        // 임꺽정 유저 생성
        member = new Member();
        member.setName("임꺽정");
        member.setUserId("lim");
        member.setUserPassword("3");
        userList.add(member);
        
        model.addAttribute("memberList", userList);

        return "userList";
    }
    
}

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

<head>
</head>
<body>
    <table border="1">
        <tr>
            <td>아이디</td>
            <td>이름</td>
            <td>비밀번호</td>
        </tr>
        <tr th:each="member : ${memberList}">
            <td th:text="${member.userId}"></td>
            <td th:text="${member.name}"></td>
            <td th:text="${member.userPassword}"></td>
        </tr>
    </table>
</body>

</html>

  • 출력 결과물

연습문제


package com.example.basic.controller;

import java.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.basic.model.Board;
import com.example.basic.model.Member;

@Controller
public class ThymleafController {
	@GetMapping("board")
    public String board(Model model) {
        ArrayList<Board> boardList = new ArrayList<>();
        Board board = new Board();
        board.setBNo(1);
        board.setTitle("첫 번째 글입니다.");
        board.setContent("첫 번째 글 테스트 내용");
        board.setUser("gil");
        boardList.add(board);

        board = new Board();
        board.setBNo(2);
        board.setTitle("두 번째 글입니다.");
        board.setContent("두 번째 글 테스트 내용");
        board.setUser("kim");
        boardList.add(board);

        board = new Board();
        board.setBNo(3);
        board.setTitle("세 번째 글입니다.");
        board.setContent("세 번째 글 테스트 내용");
        board.setUser("lee");
        boardList.add(board);

        model.addAttribute("boardList", boardList);
        return "board";
    }
    
}

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

<head>
</head>
<!-- th:each를 사용해서 게시글의 정보를 나타내는 페이지로 수정-->
<body>
    <table border="1">
        <tr>
            <td>게시글번호</td>
            <td>게시글제목</td>
            <td>내용</td>
            <td>작성자</td>
        </tr>
        <tr th:each="board : ${boardList}">
            <td th:text="${board.bNo}"></td>
            <td th:text="${board.title}"></td>
            <td th:text="${board.content}"></td>
            <td th:text="${board.user}"></td>
        </tr>
    </table>
</body>

</html>

  • 출력 결과물

조건문(Conditional Evaluation) - th:if, th:unless, th:switch

package com.example.basic.controller;

import java.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.example.basic.model.Board;
import com.example.basic.model.Member;

@Controller
public class ThymleafController {
	// th:if, th:inless, th:switch 조건문활용
    @GetMapping("mode") // http://localhost:8080/mode
    public String mode(Model model, @RequestParam Map<String,Object> map){
        // 동적인 파라미터의 데이터가 잘 들어오는지 체크를 위한 부분
        // for (String data : map.keySet()) {
        //     System.out.println("동적 파라미터 확인 : "+map.get(data));
        // }
        model.addAttribute("name", map.get("name"));
        model.addAttribute("auth", map.get("auth"));
        model.addAttribute("category", map.get("category"));
        return "mode";
    }

    // 타임리프의 조건문 활용 연습
    @GetMapping("member") ///http://localhost:8080/member?userId=1
    public String getMember(Model model, @RequestParam("userId") String userId){
        ArrayList<Member> memberList = new ArrayList<>();
        //홍길동 유저 생성
        Member member = new Member();
        member.setName("홍길동");
        member.setUserId("1");
        member.setUserPassword("123");
        memberList.add(member);
        // 이순신 유저 생성
        member = new Member();
        member.setName("이순신");
        member.setUserId("2");
        member.setUserPassword("456");
        memberList.add(member);
        // 임꺽정 유저 생성
        member = new Member();
        member.setName("임꺽정");
        member.setUserId("3");
        member.setUserPassword("789");
        memberList.add(member);

        model.addAttribute("memberList", memberList);
        model.addAttribute("userId", userId);
        return "member";
    }
    
}

  • mode.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>
<body>
    <h1> 타임리프 조건문 활용 </h1>
    관리자 이름 : 
    <span th:if="${name} != null" th:text="${name}"></span> <!-- 조건문이 참일 경우 -->
    <span th:unless="${name} != null" th:text="담당자없음"></span><br/> <!-- 조건문이 거짓일 경우 -->
    권한 :
    <!-- 삼항 연산자 사용 가능 -->
    <span th:text="${auth} != null ? ${auth} : '권한없음' "></span><br/>
    담당 카테고리 : 
    <!-- switch문 활용 -->
    <!-- 감싸는 태그에 th:switch=${데이터이름} -->
    <!-- 감싸는 태그 안쪽에 case문을 활용한다. th:case="데이터의 값"-->
    <span th:switch="${category}">
        <span th:case="1">커뮤니티</span>
        <span th:case="2">장터</span>
        <span th:case="3">갤러리</span>
    </span>
</body>

</html>

  • localhost:8080/mode?name=%ED%99%8D%EA%B8%B8%EB%8F%99&auth=gallery&category=1

  • member.html
<html xmlns:th="http://www.thymeleaf.org">

<head>
</head>

<body>
    <!-- 파라미터 userID값에 따라 해당하는 userId값과 동일한 유저정보만 출력해 봅시다.-->
    <!-- http://localhost:8080/member?userId=1일 때는 홍길동 유저의 정보만 출력되도록 작성(단, 타임리프의 조건문 활용) -->
    <table border="1">
        <tr>
            <td>아이디</td>
            <td>이름</td>
            <td>비밀번호</td>
        </tr>
        <tr th:each="member : ${memberList}">
            <span th:if="${userId} == ${member.userId}">
                <td th:text="${member.userId}"></td>
                <td th:text="${member.name}"></td>
                <td th:text="${member.userPassword}"></td>
            </span>
        </tr>
    </table>
</body>

</html>

  • localhost:8080/member?userId=1

profile
초보 개발자의 학습 저장용 블로그

0개의 댓글