TheBuriBuri
게시글
블로그
전체 52024. 02. 21.
0
과제 5
package com.group.libraryapp.controller.dice; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class DiceController { @GetMapping("/api/dice") public String dice(@RequestParam int tryCount, @RequestParam int diceCount) { int[] diceArray = rollDice(tryCount, diceCount); String ans = diceResult(diceArray); return ans; } private int[] rollDice(int tryCount, int diceCount) { int[] diceArray = new int[diceCount]; for (int i = 0; i
2024. 02. 21.
0
과제4
4-1create table fruits ( id bigint auto_increment, name varchar(20), warehousingDate date, price int, isSale boolean default 0, primary key (id) ); insert into fruits (name, warehousingDate, price) values ('사과', '2024-02-21', 1000); show tables; select * from fruits;package com.group.libraryapp.dto.fruits.request; import java.time.LocalDate; public class fruitsRequestDto { private String name; private LocalDate warehousingDate; private int price; public String getName() { return name; } public LocalDate getWarehousingDate() { return warehousingDate; } public int getPrice() { return price; } }package com.group.libraryapp.controller.fruits; import com.group.libraryapp.dto.fruits.request.fruitsRequestDto; import org.aspectj.lang.annotation.RequiredTypes; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class fruitsController { private JdbcTemplate jdbcTemplate; public fruitsController(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @PostMapping("api/v1/fruits") public void createFruits(@RequestBody fruitsRequestDto request){ String sql = "insert into fruits (name, warehousingDate, price) values (?, ?, ?)"; jdbcTemplate.update(sql, request.getName(), request.getWarehousingDate(), request.getPrice()); } } 4-2@PutMapping("/api/v1/fruits") public void updateSaleState(@RequestBody fruitSaleRequestDto request){ String saleSql = "select * from fruits where id = ?"; boolean isFruitNotExist = jdbcTemplate.query(saleSql, (rs, rowNum) -> 0, request.getId()).isEmpty(); if(isFruitNotExist){ throw new IllegalStateException("존재하지 않는 과일입니다."); } String sql = "update fruits set isSale = 1 where id = ?"; jdbcTemplate.update(sql, request.getId()); }package com.group.libraryapp.dto.fruits.request; public class fruitSaleRequestDto { private long id; public long getId() { return id; } } 4-3@GetMapping("api/v1/fruits") public List getFruitsTotalPrice(@RequestParam String name){ String sql = "select " + "(select sum(price) from fruits where isSale = 1) as salePrice, " + "(select sum(price) from fruits where isSale = 0) as noSalePrice"; return jdbcTemplate.query(sql, (rs, rowNum) -> { long salePrice = rs.getLong("salePrice"); long noSalePrice = rs.getLong("noSalePrice"); return new fruitTotalPriceDto(salePrice, noSalePrice); }); } package com.group.libraryapp.dto.fruits.request; public class fruitTotalPriceDto { private long salePrice; private long noSalePrice; public fruitTotalPriceDto(long salePrice, long noSalePrice) { this.salePrice = salePrice; this.noSalePrice = noSalePrice; } public long getSalePrice() { return salePrice; } public long getNoSalePrice() { return noSalePrice; } }
2024. 02. 21.
0
과제 3
자바의 람다식은 왜 등장했을까?자바의 람다식은 코드의 간결성과 함수형 프로그래밍의 개념을 도입하기 위해 등장했습니다. 이전에는 익명 내부 클래스를 사용하여 콜백 함수를 구현해야 했는데, 이는 코드가 복잡해지고 가독성이 떨어지는 문제가 있었습니다.람다식은 함수를 간단하고 직관적으로 표현하기 위한 방법으로, 메서드의 매개변수로 전달될 수 있고, 변수에 할당되거나 반환될 수 있습니다. 이를 통해 코드를 더욱 간결하게 작성할 수 있으며, 함수형 프로그래밍의 장점인 불변성과 병렬 처리 등을 활용할 수 있습니다.람다식은 자바 8부터 도입되었으며, 컬렉션의 필터링, 매핑, 정렬 등 다양한 연산을 간편하게 수행할 수 있게 해주었습니다. 또한, 스트림 API와 함께 사용하면 데이터를 효율적으로 처리할 수 있는 기능을 제공합니다.람다식은 자바의 발전과 현대적인 프로그래밍 패러다임에 부합하는 기능으로, 코드의 가독성과 유지보수성을 높이는 데 큰 도움을 주고 있습니다. 람다식과 익명 클래스는 어떤 관계가 있을까? - 람다식의 문법은 어떻게 될까?람다식과 익명 클래스는 서로 밀접한 관계를 가지고 있습니다.람다식은 익명 클래스의 간결한 표현입니다. 이전에는 익명 내부 클래스를 사용하여 콜백 함수를 구현했는데, 람다식은 이러한 익명 내부 클래스의 작성을 더욱 간단하게 만들어줍니다.람다식의 문법은 다음과 같습니다: (parameter) -> { body }parameter: 람다식이 사용할 매개변수의 목록입니다. 매개변수가 없을 경우에는 빈 괄호 ()를 사용합니다. 하나의 매개변수만 있다면 괄호를 생략할 수 있습니다.->: 화살표 연산자로, 매개변수와 바디를 구분합니다.body: 람다식의 실행 코드 블록입니다. 중괄호 {} 안에 구현되며, 한 줄인 경우에는 중괄호를 생략할 수 있습니다.람다식은 함수형 인터페이스를 구현하는데 주로 사용됩니다. 함수형 인터페이스는 하나의 추상 메서드만을 가지는 인터페이스를 말하며, 람다식은 이 추상 메서드를 구현하는 코드 블록으로 사용됩니다.람다식은 익명 클래스와 비교하여 코드의 길이가 짧고 가독성이 좋으며, 컴파일러에 의해 더 간결한 형태로 변환됩니다. 익명 클래스에 비해 훨씬 간편하고 효율적인 방법으로 함수형 프로그래밍을 구현할 수 있습니다.
백엔드
2024. 02. 20.
0
과제2
2-1컨트롤러 @RestController public class CalculatorAMMController { @GetMapping("/api/v1/calc") public CalculatorResponseDTO calculate(CalculatorRequestDTO request){ return new CalculatorResponseDTO(request); } }리퀘스트 package com.group.libraryapp.dto.calculator.request; public class CalculatorRequestDTO { private int num1; private int num2; public CalculatorRequestDTO(int num1, int num2) { this.num1 = num1; this.num2 = num2; } public int getNum1() { return num1; } public int getNum2() { return num2; } }레스폰스 package com.group.libraryapp.dto.calculator.response; import com.group.libraryapp.dto.calculator.request.CalculatorRequestDTO; public class CalculatorResponseDTO { private int add; private int minus; private int multiply; public CalculatorResponseDTO(CalculatorRequestDTO request) { this.add = request.getNum1() + request.getNum2(); this.minus = request.getNum1() - request.getNum2(); this.multiply = request.getNum1() * request.getNum2(); } public int getAdd() { return add; } public int getMinus() { return minus; } public int getMultiply() { return multiply; } }2-2컨트롤러 package com.group.libraryapp.controller.date; import com.group.libraryapp.dto.Date.reponse.DateResponseDto; import com.group.libraryapp.dto.Date.request.DateRequestDto; import org.springframework.web.bind.annotation.*; @RestController public class DateController { @GetMapping("/dayOfTheWeek") public DateResponseDto calculateDay(@RequestBody DateRequestDto request){ return new DateResponseDto(request); } }리퀘스트 package com.group.libraryapp.dto.Date.request; import java.time.LocalDate; public class DateRequestDto { private LocalDate date; public LocalDate getDate() { return date; } } 레스폰스 package com.group.libraryapp.dto.Date.reponse; import com.group.libraryapp.dto.Date.request.DateRequestDto; public class DateResponseDto { private String dayOfWeek; public DateResponseDto(DateRequestDto request) { this.dayOfWeek = request.getDate().getDayOfWeek().toString(); } public String getDayOfWeek() { return dayOfWeek.substring(0,3); } }2-3컨트롤러 @PostMapping("/addAllNumbers") public int addAllNumbers(@RequestBody CalculatorAddAllNumbers request){ int sum = 0; for(int i=0; i
백엔드
・
백엔드
2024. 02. 19.
0
과제 1
어노테이션을 사용하는 이유는 무엇일까?@ 시작한다.역할:스프링을 실행할 때 필요한 설정들을 자동으로 해준다.나만의 어노테이션은 어떻게 만들 수 있을까?@interface 키워드를 사용하여 어노테이션을 정의하면 됩니다 1일차 정리Java자바 공부 전 알아야할 것자바관련컴파일 : 코드 -> binary code로 변경컴파일러 : 컴파일하는 프로그램 (운영체제마다 다름)but 자바는 컴파일러(1개뿐)를 거쳐서 각 운영체제의 JVM으로 감gradlemaven1 JVM → 자바, 그루비, 스칼라, 코틀린 등에서 이용함2 JRE3 JDK → 자바의 버전,종류: ORACLE, OpenJDK 등Oracle JDK 개인은 무료 / 기업용은 유료OPenJDK 언제나 무료빌드와 실행빌드란?소스 코드 파일을 실행시킬 수 있는 하나의 파일로 만듦테스트 코드 : 내가 작성한 코드를 자동 테스트해주는 코드를 추가로 작성한 것실행 : 내가 작성한 코드를 컴파일을 거쳐 작동시키는 것인터프리터 언어는 컴파일이 필요 없음 (ex: 자바스크립트, 파이썬 등)Java의 빌드 툴빌드툴 : 빌드과정을 자동으로 해주는 프로그램외부소스 코드 자동추가, 관리ex) APACHE ANT, Gradle, MavenAntxml 사용간단하고 사용하기 쉽다복잡한 거 사용하면 관리 어려움사용 잘 안 한다.Mavenxml 사용외부 라이브러리 관리장황한 빌드 문제 해결특정경우 xml 복잡해진다.xml 자체의 한계Gradle설정을 위해 goovy(JVM 언어) 언어 사용xml 사용 x외부 라이브러리 관리유연하게 빌드 스크립트 작성가능 성능 좋다가장 최신 빌드툴Server스프링단축키option + 방향키 위 or 아래 → 적당한 영역 드래그Ctrl + option + O 안 쓰는 import 정리SOLIDSRP single resposibility principleOCP open/closed priciple 변경 x 확장 oLSP Liskov substitution principle 기능이 변경되면 안 된다?ISP interface segregation principle 인터페이스 분리 원칙DIP depency inversion principle스프링부트는 톰캣이 내장되어 있다. ( jar사용)DTO (Data transfer Object) 데이터 전달 객체프레임워크미리 만들어져있는 구조에 코드를 끼워 넣는 것annotation@ 시작한다.역할:스프링을 실행할 때 필요한 설정들을 자동으로 해준다.ServerServe + er → 제공하는 것(기능)요청에 대한 기능을 제공하는 것인터넷, 네트워크를 통해 요청한다.네트워크컴퓨터는 각각의 고유주소(IP)를 가지고 있다. ex 123.1.22.19인터넷을 통해 데이터를 컴퓨터끼리 주고받음DNS (Domain Name System)데이터를 받는 컴퓨터 IP 244.66.51.9, port :3000port = 사용하는 프로그램을 가르킴한 프로그램은 1포트를 사용함.도메인 244.66.51.9 같은 숫자 대신 이름을 넣는다.ex) spring.com, port:3000즉 244.66.51.9 = 도메인 이름.com운송장HTTP (Hyper Text Transfer Protocol)HTTP 요청 (데이터 요청)GET /portion?color=red&count=2Host:spring.com:3000 (헤더) 여러줄도 가능→ 달라/ 패스(자원) ? 세부조건 & 다른 세부조건 (쿼리)요청을 받는 컴퓨터와 프로그램 정보 (3000번 프로그램)HTTP 요청을 보내기 전에 미리 약속을 해야함받을 공간 마련POST → 요청을 받는 컴퓨터가 데이터를 저장자원의 정보 저장할 때POST → Body(바디)PUT (수정해라) → Body(바디)원하는 정보 달라할 때GET → Query(쿼리)DELETE → Query(쿼리)API (Application Programming Interface) (정해진 규칙)미리 물건을 주거나, 저장할 수 있도록 준비가 되어 있어야함.HTTP 문법을 사용함@RestController → API 의 진입 지점을 만듦@GetMapping → http method Get쿼리를 할 때 각각의 파라미터 앞에 @RequestParam 이라 적어준다.URL (Uniform Resource Locator)http://spring.com:3000/portion?color=red?count=2http → 약속 프로토콜// → 구분기호spring.com:3000 → 도메인 이름 (IP로 대체 가능)portion = Path(자원의 경로)? → 구분기호color=red?count=2 쿼리(추가정보)클라이언트 - 서버 구조 (응답)정보 처리후 200 OK를 보냄 (정보를 저장했어)요청에 대한 응답을 제공한 컴퓨터 = 서버요청한 컴퓨터 Client상태코드200 OK300영구적으로 옮겨404찾을 수 없음500내부의 문제가 생겼어응답에는 바디를 담을 수 있음응답 구조요청 - 응답
백엔드
・
1일차