본문 바로가기
🍃SpringFrameworks/SpringBoot

[SpringBoot] 주요 개념 정리

by inbeom 2023. 8. 20.
728x90

💡 Optional

'null일 수도 있는 객체'를 감싸는 일종의 Wrapper 클래스이다.

  • • optional 변수 내부에는 null이 아닌 T 객체가 있을 수도 있고 null이 있을 수도 있다.
  • 따라서, Optional 클래스는 여러 가지 API를 제공하여 null일 수도 있는 객체를 다룰 때 사용한다.
// 1) Optional 객체 생성
Optional<User> result = userRepository.findById(userId);

// 2) Optional 객체 접근
if(result.isPresent()) {
                return result.get();
            }else{
                return result.orElse(null);
// Optional객체에 담긴 값이 있으면 객체 내부의 값을 반환.
// 만약, null인 객체라면 NoSuchElementException이 발생

JPA에서 Entity의 속성(변수)을 PrimitiveType(int, float~)으로 지정하면 NULL값을 받을 수 있지만, WrapperClass (Long, Float~) 로 생성하면 NULL값을 허용하지 않는다.


 

💡 FrontFile 연결 방법!!

파일 삽입 위치

src → main → resources →

templates : HTML 파일

static : JavaScript, CSS 파일

  • Ex>


  • PageController 파일을 따로 만들어 GetMapping한다.
  • 이때 ModelAndView를 반환 타입으로 지정하고 ModelAndView타입의 객체를 생성해 return해줌.
@Controller
@RequestMapping("/pages")
public class PageController {

@GetMapping("/main")
	public ModelAndView main() { // 타임리프에서 특정한 HTML View로 보낼 때 사용
		return new ModelAndView("aaaa/main"); // resources -> templates 폴더 하위의 경로
	}
}

 

💡 RestTemplate

Get으로 (server와) 통신.

public UserResponse hello(){
	// UriComponentsBuilder 를 사용하여 URL 작성
	URI uri = UriComponentsBuilder
		.fromUriString("[<http://localhost:9090>](<http://localhost:9090/>)")
		.path("/api/server/hello")
		.queryParam("name", "steve")
		.queryParam("age", 99)
		.encode()
		.build()
		.toUri();
	System.out.println(uri.toString());

	RestTemplate restTemplate = new RestTemplate();
	// getForEntity == 주어진 URL에서 ResponseEntity타입으로 값을 반환받음.
	ResponseEntity<UserResponse> result = restTemplate.getForEntity(uri, UserResponse.class);

	System.out.println(result.getStatusCode());
	System.out.println(result.getBody());

	return result.getBody();
}

 

💡 HttpServletRequest & HttpServletResponse

 

WAS가 웹브라우저로부터 Servlet요청을 받으면

  1. 요청을 받을 때 전달 받은 정보를 HttpServletRequest객체를 생성하여 저장
  2. 웹브라우져에게 응답을 돌려줄 HttpServletResponse객체를 생성(빈 객체)
  3. 생성된 HttpServletRequest(정보가 저장된)와 HttpServletResponse(비어 있는)를 Servlet에게 전달

HttpServletRequest

  1. Http프로토콜의 request 정보를 서블릿에게 전달하기 위한 목적으로 사용
  2. Header정보, Parameter, Cookie, URI, URL 등의 정보를 읽어들이는 메소드를 가진 클래스
  3. Body의 Stream을 읽어들이는 메소드를 가지고 있음

HttpServletResponse

  1. Servlet은 HttpServletResponse객체에 Content Type, 응답코드, 응답 메시지등을 담아서 전송함
728x90