Spring MVC를 이용한 웹 페이지 작성 실습 - Exam 1
목표
- 웹 브라우저에서 http://localhost:8080/mvcexam/plusform 이라고 요청을 보내면 서버는 웹 브라우저에게 2개의 값을 입력받을 수 있는 입력 창과 버튼이 있는 화면을 출력한다.
- 웹 브라우저에 2개의 값을 입력하고 버튼을 클릭하면 http://localhost:8080/mvcexam/plus URL로 2개의 입력값이 POST방식으로 서버에게 전달한다. 서버는 2개의 값을 더한 후, 그 결과 값을 JSP에게 request scope으로 전달하여 출력한다.
Spring MVC가 지원하는 메소드 인수 애노테이션
@RequestParam
- Mapping된 메소드의 Argument에 붙일 수 있는 애노테이션
- @RequestParam의 name에는 http parameter의 name과 맵핑
- @RequestParam의 required는 필수인지 아닌지 판단
@PathVariable
- @RequestMapping의 path에 변수명을 입력받기 위한 placeholder가 필요함
- placeholder의 이름과 PathVariable의 name 값과 같으면 mapping 됨
- required 속성은 defualt true임
@RequestHeader
- 요청 정보의 헤더 정보를 읽어들일 때 사용
ex) @RequestHeader(name="헤더명") String 변수명
View 작성
# plusForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="plus">
value1 : <input type="text" name="value1"><br>
value2 : <input type="text" name="value2"><br>
<input type="submit" value="확인">
</form>
</body>
</html>
# plusResult.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${value1} 더하기 ${value2} (은/는) ${result} 입니다.
</body>
</html>
Controller 작성
# PlusController.java
package com.example.mvcexam.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class PlusController {
@GetMapping("/plusform")
public String plusform() {
// 요청이 들어왔을 때, 해당 뷰의 이름만 알려주면 됨
// ViewResolver가 이름에 파일의 경로를 붙여줄 거임
return "plusForm";
}
@PostMapping("/plus")
public String plus(@RequestParam(name = "value1", required = true) int value1,
@RequestParam(name = "value2", required = true) int value2,
ModelMap modelMap) {
int result = value1 + value2;
// HttpServletRequest, HttpServletResponse가 아닌 ModelMap에 넣어주면 Spring이 알아서 매핑해줌
modelMap.addAttribute("value1", value1);
modelMap.addAttribute("value2", value2);
modelMap.addAttribute("result", result);
return "plusResult";
}
}
실행 결과


Spring MVC를 이용한 웹 페이지 작성 실습 - Exam 2
목표
- http://localhost:8080/mvcexam/userform 으로 요청을 보내면 이름, email, 나이를 물어보는 폼이 보여진다.
- 폼에서 값을 입력하고 확인을 누르면 post방식으로 http://localhost:8080/mvcexam/regist 에 정보를 전달하게 된다.
- regist에서는 입력받은 결과를 콘솔 화면에 출력한다.
View 작성
# userForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="regist">
name : <input type="text" name="name"><br>
email : <input type="text" name="email"><br>
age : <input type="text" name="age"><br>
<input type="submit" value="확인">
</form>
</body>
</html>
# regist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Main Page</title>
</head>
<body>
<h1>등록되었습니다!</h1>
</body>
</html>
DTO 작성
# User.java
package com.example.mvcexam.dto;
public class User {
private String name;
private String email;
private int age;
public User(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
Controller 작성
# UserController.java
package com.example.mvcexam.controller;
import com.example.mvcexam.dto.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class UserController {
@GetMapping("/userform")
public String userform() {
return "userForm";
}
@PostMapping("/regist")
public String regit(@ModelAttribute User user) { // 파라미터를 하나씩 받아오는 게 아니라, DTO를 통해 객체로 받아옴
System.out.println("사용자가 입력한 user 정보입니다. 해당 정보를 이용하는 코드가 와야합니다.");
System.out.println(user);
return "regist";
}
}
실행 결과



Spring MVC를 이용한 웹 페이지 작성 실습 - Exam 3
목표
- http://localhost:8080/mvcexam/goods/{id} 으로 요청을 보낸다.
- 서버는 id를 콘솔에 출력하고, 사용자의 브라우저 정보를 콘솔에 출력한다.
- 서버는 HttpServletRequest를 이용해서 사용자가 요청한 PATH정보를 콘솔에 출력한다.
View 작성
#goodsById
goodsById.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
id : ${id } <br>
user_agent : ${userAgent }<br>
path : ${path }<br>
</body>
</html>
Controller 작성
# GoodsController.java
package com.example.mvcexam.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
@Controller
public class GoodsController {
@GetMapping("/goods/{id}")
public String getGoodsById(@PathVariable(name = "id") int id,
@RequestHeader(value = "User-Agent", defaultValue = "myBrowser") String userAgent,
HttpServletRequest request,
ModelMap model) {
String path = request.getServletPath();
System.out.println("id: " + id);
System.out.println("userAgent : " + userAgent);
System.out.println("path: " + path);
model.addAttribute("id", id);
model.addAttribute("userAgent", userAgent);
model.addAttribute("path", path);
return "goodsById";
}
}
실행 결과


'강의 노트 > 웹 프로그래밍(풀스택)' 카테고리의 다른 글
[boostcourse] 3.10. Layered Architecture - BE (2) (0) | 2023.06.27 |
---|---|
[boostcourse] 3.10. Layered Architecture - BE (1) (0) | 2023.06.27 |
[boostcourse] 3.9. Spring MVC - BE (1) (0) | 2023.06.26 |
[boostcourse] 3.8. Spring JDBC - BE (0) | 2023.06.25 |
[boostcourse] 3.7. Spring Core - BE (0) | 2023.06.24 |