📅 공부 기간 : 08. 20(화)
💡 tip : HTML(클라이언트) --> Controller(서버)
param/send? : 요청name=Mike&age=25 : 파라미터<ul>
<li><a href="param/send?name=Mike&age=25">a 태그로 Parameter 송신</a></li>
</ul>
<ul>
<li><a href="param/send">a 태그로 Parameter 없이 송신</a></li>
</ul>
@GetMapping : GET 요청 처리@RequestParam : 클라이언트에서 받은 데이터를 서버에서 받기 위해 사용.defaultValue : 클라이언트에서 받은 값이 없을 때 설정할 기본 값public class ParamController {
@GetMapping("/param/send")
public String param(
@RequestParam(name="name", defaultValue="홍길동") String name,
@RequestParam(name="age", defaultValue="20") int age
) {
System.out.println("name=" + name + ", age= " + age);
return "result"; // 성공하면 result.html 반환
}
}
GET 방식
URL에 데이터를 포함하기 때문에 브라우저의 주소창에 정보가 노출됨.
<form action="param/sendForm" method="GET">
<label for="userid">아이디: </label>
<input type="text" name="userid" id="userid" placeholder="아이디 입력">
<label for="userpwd">비밀번호: </label>
<input type="password" name="userpwd" id="userpwd" placeholder="비밀번호 입력">
<br><br>
<input type="submit" value="전송">
<input type="reset" value="취소">
</form>
@Controller
public class ParamController {
@GetMapping("/param/sendForm")
public String sendForm(
@RequestParam(name="userid", defaultValue="abc") String userid,
@RequestParam(name="userpwd", defaultValue="korea") String userpwd
) { // id=>abc, passwd=>korea
System.out.println("userid=" + userid + ", userpwd= " + userpwd);
return "result";
}
}
POST 방식
- 데이터를 HTTP 요청의 본문(Body)에 담아서 전송
- URL에 데이터가 포함되지 않음.
- 보안에 유리
<form action="param/sendForm" method="POST">
<label for="userid">아이디: </label>
<input type="text" name="userid" id="userid" placeholder="아이디 입력">
<label for="userpwd">비밀번호: </label>
<input type="password" name="userpwd" id="userpwd" placeholder="비밀번호 입력">
<br><br>
<input type="submit" value="전송">
<input type="reset" value="취소">
</form>
@PostMapping : POST 요청 처리model.addAttribute() : Model 객체에 데이터 추가@Controller
public class ParamController {
@PostMapping("/param/sendForm")
public String sendForm2(
@RequestParam(name="userid", defaultValue="abc") String userid,
@RequestParam(name="userpwd", defaultValue="korea") String userpwd,
Model model
) { // id=>abc, passwd=>korea
System.out.println("userid=" + userid + ", userpwd= " + userpwd);
model.addAttribute("id", userid);
model.addAttribute("pwd", userpwd);
return "receive"; // forward 방식
}
}
⭐️ tip : form태그에서 같은 요청
("/param/sendForm/")이 있으면 안되지만, method(GET, POST)가 다르면 괜찮음.
forward 방식
[[ ${id} ]])<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Model에서 데이터 꺼내기</title>
</head>
<body>
<h2>Model에서 데이터 꺼내기</h2>
<p>
html 문서는 Model의 값을 꺼낼 수 없다. <br>
그래서 thymeleaf 문법을 사용해야 한다.
</p>
<p>
아이디 : [[ ${id} ]] <br>
비밀번호 : [[ ${pwd} ]]
</p>
</body>
</html>
th:href=”@{/display/text}”