스프링의 정석 : 남궁성과 끝까지 간다 학습 내용 정리

package com.mytistory.ch2;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Controller
public class GetBirthday {
	@RequestMapping("/getBirth")
	public void main(HttpServletRequest request, HttpServletResponse response) {
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String day = request.getParameter("day");
		
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out=null;
		try {
			out = response.getWriter();
		}
		catch(IOException e) {
			return;
		}
		out.println("생년월일은: "+year+"년 "+month+"월 "+day+"일 입니다.");
		
	}
}

톰캣 서버로 실행 후 브라우저에서 http://localhost:8080/getBirth?year=2021&month=10&day=1 (request)

다음과 같이 URL 입력 시: 톰캣 서버가 요청을 받고 HttpServletRequest 객체와 HttpServletResponse 객체를 생성할 때  굵은 글시체 부분(쿼리 스트링)이 전달이 되어

getParameter() 함수를 통해 해당 String을 가지고 온다. 

 

HttpServletResponse 객체의 메소드 활용

setContentType("text/html"), setCharacterEncoding("utf-8") 을 통해 데이터 형식과 인코딩 방식을 알려주고

(+ 브라우저는 보내는 내용이 text인지 binary 인지 모르기 때문에 명시를 해주어야 한다.)

getWriter()를 통해 출력 스트림을 가지고 와서 해당 브라우저로 출력

 

PrintWriter: 자바에서 문자 단위 입출력을 위한 하위 스트림 클래스  

'Development > Spring' 카테고리의 다른 글

Spring의 4개의 저장소  (0) 2023.01.19
HTTP 프로토콜의 바이너리 파일 전송  (0) 2023.01.08
웹과 HTTP 프로토콜  (0) 2023.01.06
클라이언트와 서버  (0) 2023.01.05
Spring 원격 프로그램 실행 과정  (0) 2023.01.04

+ Recent posts