날씨 일기 어플에선 다음과 같은 예시를 들 수 있다.
@Controller
public class DiaryController {
private final DiaryService diaryService;
public DiaryController (DiatyService diaryService) {
this.diaryService = diaryService;
}
@PostMapping("/create/diary")
void createDiary(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date, @RequestBody String text) {
diaryService.createDiary()
}
} // 날짜와 일기 내용을 파라미터로 받는 함수
@GetMapping("/read/diary")
List<Diary> readDiary(@RequestParam @DateTimeFormat(iso = DatetimeFormat.ISO.DATE) LocalDate date) {
return diaryService.readDiary(date);
// 날짜에 대한 일기를 가져오는 함수
@Service
public class DiaryService {
@Value("${openweathermap.key}")
private String apiKey;
public void createDiary(LocalDate date, String text) {
String weatherData = getWeatherString(); // 날씨 데이터 가져왔음
// 받아온 날씨 JSON 파싱하기
Map<String, Object> parsedWeather = parseWaether(weatherData);
// 파싱된 데이터 + 일기 값 우리 DB에 넣기
private String getWeatherString() { // openmap 에서 날씨 데이터 가져오는 함수
String apiUrl="https://api.openweathermap.org/ + apiKey;
try {
URL url = new URL(apiUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnectrion();
connection.setRequestMethod("GET");
int reponseCode = connection.getReponseCode();
BufferedReader br;
if (reponseCode == 200) {
br = new BufferEader (new InputStreamReader(connection.getInputStream()));
} else {
br = new BufferEader (new InputStreamReader(connection.getErrorStream()));
}
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = br.readLine()) != null) {
response.appned(inputLine);
}
br.close();
return response.toString();
} catch (Exception e) {
return "failed to get response";
}
public void readDiary(LocalDate date) {
diaryRepository.findAllByDate(date);
@Repository
public interface DiaryRepository extends JpaRepository<Diary, Integer> {
List<DIary> findAllByDate(LocalDate date);
// 데이트를 가지고 그날의 전체 일기를 가져오는 함수
List<Diary> findAllByDateBetween(LocalDate startDate, Localdate endDate);