본문 바로가기

코딩 학원(국비지원)

58일차 코딩학원

반응형

1. 서울 황사수치 193... 그런데 마스크를 안챙겼다. 코가 쓰리다. 

2. 쿠키(Cookie)와 세션(Session) 내용 정리 

 

쿠키 vs 세션 

           쿠키(Cookie)                 세션(HttpSession)
        -------------------------------------------------------------
            브라우저 저장                      서버 저장 
            서버 부담 X                          서버 부담 O
            보안에 불리                          보안에 유리 
            서버다중화에 유리               서버 다중화에 불리 

 

3. 예외처리 개념 정리가 필요하다. 오늘 Java의 정석 강의 듣기. 

 

4. Spring에서 만든 객체는 singleton패턴이다. 

 

5. Spring에서 예외처리. 이렇게 작성하면 500 오류가 나온다. 서버에 문제가 있다는 뜻이다. 

package com.earth.duststrom;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController {
	
	@RequestMapping("/ex_")
	public void earth() throws Exception {
		throw new Exception("예외가 발생했습니다.");
	}
}

 

6. 다시 처리해보자. 

 

컨트롤러파일

package com.earth.duststrom;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExceptionController {
	
	@RequestMapping("/ex_")
	public void earth() throws Exception {
	
	try {
		throw new Exception("예외가 발생했습니다.");
	}catch (Exception e) {
		
		e.printStackTrace();
		}
	}
	
	
}

 

view 파일 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
	 <h1>예외가 발생했습니다.</h1>
</body>
</html>

 

결과 

 

7. 위와 같이 try~catch로 처리할 수도 있지만 다른 방법도 있다. @ExceptionHandler 다. 

 

8. @ExceptionHandler 
        - 예외 처리를 위한 메서드 작성하고 @ExceptionHandler를 설정
        - 컨트롤러에 @ExceptionHandler 메서드가 예외 처리함 

 

같은 class 내부의 예외만 예외처리가 가능하다. 

 

9. 일단 따라가고 있음. 무슨 소리인지 약간 이해가 안되지만... 

10. @ResponseStatus

예외 처리 메서드에 응답 메서드의 상태 코드를 변경할 때 사용

 

11. 예제 

package com.earth.finedust;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.BAD_REQUEST)
class MyException extends RuntimeException {
	public MyException(String msg) {
		super(msg);
	}
	
	public MyException() {
		this(""); 
	}
}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
class MyException2 extends RuntimeException {
	public MyException2(String msg) {
		super(msg);
	}
	
	public MyException2() {
		this(""); 
	}
}
/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		return "home";
	}
	
	
	@RequestMapping("/test")
	public String earth(Model m) {
		throw new MyException("사용자 정의 예외가 발생했습니다.");
	}
	
	@RequestMapping("/test2")
	public String earth2(Model m) {
		throw new MyException2("사용자 정의 예외가 발생했습니다.");
	}
}

 

webapp에 error400, error500 jsp파일 만들기

 

 

12. 스프링부트 연습 중. url = https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.7.10&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=dayoftheweek&name=dayoftheweek&description=dayoftheweek%20project%20for%20Spring%20Boot&packageName=com.example.dayoftheweek&dependencies=devtools,web,thymeleaf

 

13. public String dayweek(int year, int month, int day, Model model) { } 여기서 모델 객체를 왜 넣지?

 

dayweek 메소드에서 Model 객체가 매개변수로 전달되는 이유는, 해당 메소드에서 계산한 결과를 뷰에 전달하기 위해서입니다.

Model 객체는 컨트롤러에서 뷰로 데이터를 전달하는 데 사용되는 인터페이스입니다. 컨트롤러에서 Model 객체를 생성하고 데이터를 추가하면, 이후 뷰에서는 해당 데이터를 참조하여 뷰를 렌더링할 수 있습니다.

즉, dayweek 메소드에서는 year, month, day 매개변수를 이용해 요일을 계산하고, 이를 Model 객체에 추가하여 뷰로 전달하려는 것으로 추측됩니다. 따라서 해당 메소드에서 계산한 요일 정보를 뷰에서 사용하려면, Model 객체를 매개변수로 전달하여 데이터를 전달해야 합니다.

 

반응형

'코딩 학원(국비지원)' 카테고리의 다른 글

60일차 코딩학원  (1) 2023.04.15
59일차 코딩학원  (1) 2023.04.13
57일차 코딩학원  (2) 2023.04.11
56일차 코딩학원  (2) 2023.04.10
55일차 코딩학원  (0) 2023.04.07