230314_강의 메모

왕감자·2023년 3월 15일
1

강의 메모

목록 보기
6/6

Springboot

스프링부트는 웹 프로그램을 쉽고 빠르게 만들어 주는 웹 프레임워크다.

Spring Initializr

Spring Initializr 사이트 링크

스프링에서 제공하는 웹 도구를 사용해서 사이트를 통해서 스프링 프로젝트를 만드는 방법

  • Project: Gradle - Groovy
  • Language: Java
  • Spring Boot: 3.0.4
  • Packaging: Jar
  • Java: 17

Dependencies 추가

  • Spring Boot DevTools
  • Lombok
  • Spring Web
  • Thymeleaf

프레임워크와 라이브러리의 차이

  • 프레임워크: 자유도가 낮고 빠르다.
  • 라이브러리: 자유도가 높고 느리다. → 무언가를 하나 만들 때 모든 고민을 자신이 해야 한다.

스프링부트 프로젝트 실행

  1. 인텔리제이에서 Run
  2. 브라우저(크롬)를 켜고 http://localhost:8080으로 접속

HomeController 예제

컨트롤러의 의미

  • 고객(브라우저)의 요청을 수집하고, 관련부서로 토스해 주는 역할을 한다.
  • 관련부서에서 해당일을 처리하여 컨트롤러에서 다시 알려주면, 컨트롤러는 그 내용을 다시 고객(브라우저)가 이해할 수 있는 형태로 바꿔서 최종적으로 고객에 게 응답한다.
  • 은행으로 비유하면, 창구에 앉아서 고객과 직접적으로 소통하는 창구직원에 비유할 수 있다.
// 기본 예제
@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 설정을 하면 생략이 가능하다.

  • a는 URL에서 생략이 가능하다. (ex: /home/plus?b=20)
  • b는 URL에서 생략이 불가능하다. (ex: /home/plus?a=10)

// 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);
    }
}

HttpServletRequest와 HttpServletResponse 객체

  • HttpServletRequest: 받은 편지 브라우저에서 보내온 쿠키들에 접근하고 싶다면 req.getCookies(); 라고 쓰면된다.
  • HttpServletResponse: 보낼 편지 브라우저에 쿠키를 추가하거나, 브라우저에 있는 기존 쿠키를 수정하고 싶다면,  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;
    }
}
profile
감자 심기

0개의 댓글