[스프링 프레임워크 첫걸음] ( 7 / 9 )

박북velog·2023년 4월 23일
0

제 7장 요청 파라미터 취득하기


7.1 요청 파라미터의 종류

7.1.1 요청 파라미터란 ?

서버에 전송되는 값을 요청 파라미터 (request parameter) 라고 한다.

요청 파라미터내용
요청 쿼리 스트링( query string ) 으로 보내지는 값 GET으로 서버 데이터 전송뷰에서 입력값 및 선택 값이나 숨김 파라미터 등에서 미리 뷰에서 입력해둔 값 등
요청 본문( body )에 저장되어 보내지는 값 POST로 서버 데이터 전송뷰에서 입력값 및 선택 값이나 숨김 파라미터 등에서 미리 뷰에서 입력해둔 값 등
뷰에서 클릭한 버튼의 name 속성 값하나의 뷰에 버튼이 여러 개 있을 때 어느 버튼인지 판별할 수 있는 값
URL 경로의 일부로 보내지는 값링크 등으로 URL의 일부로 보내지는 값

7.1.2 요청 파라미터의 취득 방법

방법내용
@RequestParam 사용@RequestParam 어노테이션을 이용해 파라미터를 하나씩 취득
Form 클래스 사용 ( Form 클래스 따로 만들기 )스프링 MVC가 Form 클래스 내의 필드에 대해 값을 저장한다. 요청 파라미터를 모아서 하나의 객체로 받아들이기 때문에 자주 사용되는 방법. 받을 때 '형변환' 이나 '포멧 지정' 이 가능하다.

7.2 (1) 입력값 받는 프로그램 만들기 ( @RequestParam )

1. 컨트롤러 생성하기

@Controller
public class RequestParamController {
	@GetMapping("show")
    public String showView() {
    	// 반환 값으로 뷰 이름을 돌려줌
        return "entry";
    }
}

2. 뷰 생성 ( 입력 화면 )

showView 메서드의 반환 값인 '뷰 이름 : entry'에 대응하는 entry.html을 생성

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"> // 타임리프 사용 선언
<head>
  <meta charset="UTF-8">
  <title>입력 화면</title>
</head>
<body>
<form th:action="@{/confirm}" method="post"> // confirm URL로 보낸다
  <div>
    <label for="name">이름:</label>
    <input type="text" name="name">
  </div>
  <div>
    <label for="age">나이:</label>
    <input type="number" name="age" min="1" max="100"> // type=number 숫자만 입력할 수 있다.
  </div>
  <div>
    <label for="birth">생년월일:</label>
    <input type="date" name="birth"> // value 값 형식 : 'yyyy-MM-dd'
  </div>
  <input type="submit" value="전송">
</form>
</body>
</html>

3. 컨트롤러에 추가

@PostMapping("confirm")
public String confirmView (
	Model model, @requestParam String name, @RequestParam Integer age,
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) @RequestParam LocalDate birth) {
    // Model 에 저장
    model.addAttribute("name", name);
    model.addAttribute("age", age);
    model.addAttribute("birth", birth);
    
    // 반환값으로 뷰 이름 돌려줌
    return "confirm";
}

뷰에서 type="date" 의 값은 항상 'yyyy-MM-dd' 형식이기 때문에 @DateTimeFormat 으로
iso = DateTimeFormat.ISO.DATE를 지정해서 날짜 형식 받음

4. 뷰 생성 ( 확인 화면 )

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title> 확인 화면 </title>
</head>
<body>
  <ul>
    <li>이름 	 : [[${name}]]</li>
    <li>나이 	 : [[${age}]]</li>
    <li>생년월일  : [[${birth}]]</li>
  </ul>
</body>
</html>

7.2 (2) 입력값 받는 프로그램 ( Form 클래스 생성 )

1. Form 클래스 생성

@Data
public class Form {
	private String name;
    private Integer age;
    
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate birth;
}

2. 컨트롤러 추가

@PostMapping("confirm")
public String confirmView(Form f) {
	// 반환값으로 뷰 이름을 돌려준다.
    return "confirm2";
}

3. 뷰 생성 ( Form 클래스 확인 화면 )

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title> 확인 화면 Form 클래스 사용 </title>
</head>
<body>
  <ul>
    <li>이름 	 : [[${form.name}]]</li>
    <li>나이 	 : [[${form.age}]]</li>
    <li>생년월일  : [[${form.birth}]]</li>
  </ul>
</body>
</html>

7.3 URL 에 포함된 값을 받는 프로그램 만들기

1. 컨트롤러 생성

@Controller
public class PathVariableController {

	@GetMapping("show")
    public String showView() {
    
    	return "show";
    }
}

2. 뷰 생성 ( 입력 화면 )

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title> URL 경로에 포함된 값과 클릭된 버튼 식별 </title>
</head>
<body>
<div>
  <!-- URL 에 값 넣기 -->
  <h3><a th:href="@{/function/1}">기능-1</a></h3>
  <h3><a th:href="@{/function/2}">기능-2</a></h3>
  <h3><a th:href="@{/function/3}">기능-3</a></h3>
  <!-- 같은 form 태그 안에 포함된 여러개의 버튼 -->
  <form th:action="@{/send}" method="post">
    <input type="submit" value="버튼A" name="a">
    <input type="submit" value="버튼B" name="b">
    <input type="submit" value="버튼C" name="c">
  </form>
</div>
</body>
</html>

form 태그 안에 3개의 버튼을 클릭하면 URL(/send) 로 POST 송신된다.

3. 컨트롤러에 추가 ( 링크 처리 )

@GetMapping("/function/{no}")
public String selectFunction(@pathVariable Integer no) {
	// 뷰 이름을 초기화
    String view = null;
    switch (no) {
    	case 1:
        	view = "pathvariable/function1";
            break;
        case 2:
        	view = "pathvariable/function2";
            break;
        case 3:
        	view = "pathvariable/function3";
            break;
    }
     
     return view;
}

@GetMapping("/function/{no}") 가 GET으로 온 URL(/function/{no}) 에 대응한다.

4. 뷰 생성 ( 기능 화면 )

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title> 기능 1 </title>
</head>
<body>
  <h1>기능 1의 화면</h1>
</body>
</html>

function1.html
같은 방법으로 2, 3을 생성할 수 있다.

5. 컨트롤러에 추가 ( 버튼 판별 처리 )

// 버튼 A 클릭 처리
@PostMapping(value = "send", params = "a")
public String showAView() {
	return "submit/a";
}

// 버튼 B 클릭 처리
@PostMapping(value = "send", params = "b")
public String showBView() {
	return "submit/b";
}

// 버튼 C 클릭 처리
@PostMapping(value = "send", params = "c")
public String showCView() {
	return "submit/c";
}

6. 뷰 생성 ( 버튼 클릭 확인 화면 )

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title> a </title>
</head>
<body>
  <h1>버튼 A클릭 화면</h1>
</body>
</html>

A.html
같은 방법으로 B, C를 생성할 수 있다.

profile
느리지만 끝까지 해보자구

0개의 댓글