⭐ 스프링부트는 웹 프로그램을 쉽고 빠르게 만들어 주는 웹 프레임워크다.
스프링에서 제공하는 웹 도구를 사용해서 사이트를 통해서 스프링 프로젝트를 만드는 방법
Dependencies 추가
컨트롤러의 의미
// 기본 예제
@Controller
public class HomeController {
// @GetMapping("/home/main") 의 의미
// 개발자가 스프링부트에게 말한다.
// 만약에 /home/main 이런 요청이 오면 아래 메서드를 실행해줘
@GetMapping("/home/main")
// @ResponseBody 의 의미
// 아래 메서드를 실행한 후 그 리턴값을 응답으로 삼아줘
@ResponseBody
public String showMain() {
return "안녕하세요.";
}
@GetMapping("/home/main2")
@ResponseBody
public String showMain2(){
return "반갑습니다.";
}
@GetMapping("/home/main3")
@ResponseBody
public String showMain3(){
return "즐거웠습니다.";
}
}
// /home/increase 또는 /home/decrease에 접속할 때마다 count 값이 변하는 예제
public class HomeController {
int count = 0;
// 리턴되는 int 값은 스프링부트가 알아서 String화 되어서 고객에게 전달.
@GetMapping("/home/increase")
@ResponseBody
public int increase(){
int ans = this.count;
count = count + 1;
return ans;
}
@GetMapping("/home/decrease")
@ResponseBody
public int decrease(){
int ans = this.count;
count = count - 1;
return ans;
}
}
// RequestParam 예제
public class HomeController {
/*
@RequestParam의 의미
int a 는 쿼리스트링에서 a 파라미터의 값을 얻은 후 정수화 한 값이어야 한다.
생략가능 */
@GetMapping("/home/plus")
@ResponseBody
public int plus(@RequestParam(defaultValue = "0") int a, @RequestParam int b){
return a + b;
}
}
✔️defaultValue 설정을 하면 생략이 가능하다.
// People 클래스 생성, 수정, 삭제 컨트롤러 예제
public class HomeController {
List<People> PeopleList = new ArrayList<>();
@GetMapping("/home/addPerson")
@ResponseBody
public String addPerson(@RequestParam(defaultValue = "이름 없음") String name, @RequestParam(defaultValue = "0") int age){
People Person1 = new People(name, age);
PeopleList.add(Person1);
int id = Person1.getId();
return id + "번 사람이 추가되었습니다.";
}
@GetMapping("/home/people")
@ResponseBody
public List<People> showPeople(){
return PeopleList;
}
@GetMapping("/home/removePerson")
@ResponseBody
public String removePeople(@RequestParam int id){
boolean isRemoved = PeopleList.removeIf(people -> people.getId() == id);
if(isRemoved == true){
return id + "번 사람이 삭제되었습니다.";
} else {
return id + "번 사람이 존재하지않습니다.";
}
}
@GetMapping("/home/modifyPerson")
@ResponseBody
public String modifyPeople(int id, String name, int age){
People found = PeopleList.stream()
.filter(p -> p.getId() == id)
.findFirst()
.orElse(null);
if (found ==null){
return id + "번 사람이 존재하지않습니다.";
} else {
found.setName(name);
found.setAge(age);
return id + "번 사람이 수정되었습니다.";
}
}
}
// People 클래스 생성, 수정, 삭제 컨트롤러 예제
// 모든 멤버 변수를 매개변수로 갖는 생성자를 자동으로 생성
// 클래스의 모든 멤버 변수 Getter 생성
@AllArgsConstructor
@Getter
class People {
private static int lastid;
private int id;
@Setter
private String name;
@Setter
private int age;
static{
lastid = 0;
}
People(String name, int age){
this(++lastid, name, age);
}
}
req.getCookies();
라고 쓰면된다.resp.addCookie(new Cookie("쿠키이름", "쿠키값"));
라고 쓰면 된다.// HttpServletRequest, HttpServletResponse 예제
public class HomeController {
@GetMapping("/home/reqAndResp")
@ResponseBody
public void showReqAndResp(HttpServletRequest req, HttpServletResponse resp) throws IOException {
int age = Integer.parseInt(req.getParameter("age"));
resp.getWriter().append("Hello, you are %d years old.".formatted(age));
}
@GetMapping("/home/cookie/increase")
@ResponseBody
public int showCookieIncrease(HttpServletRequest req, HttpServletResponse resp) throws IOException { // 리턴되는 int 값은 String 화 되어서 고객(브라우저)에게 전달된다.
int countInCookie = 0;
// 고객이 가져온 쿠폰에서 count 쿠폰을 찾고 그 쿠폰의 값을 가져온다.
if (req.getCookies() != null) {
countInCookie = Arrays.stream(req.getCookies())
.filter(cookie -> cookie.getName().equals("count"))
.map(cookie -> cookie.getValue())
.mapToInt(Integer::parseInt)
.findFirst()
.orElse(0);
}
int newCountInCookie = countInCookie + 1;
// 고객이 가져온 count 쿠폰 값에 1을 더한 쿠폰을 만들어서 고객에게 보낸다.
// 쉽게 말하면 count 쿠폰의 값을 1 증가 시킨다.
resp.addCookie(new Cookie("count", newCountInCookie + ""));
return newCountInCookie;
}
}