[Spring] 01. AWS/HTTP요청과 응답/클라이언트와 서버/설정파일

Hyeongmin Jung·2023년 5월 2일
0

Spring

목록 보기
1/17

🐣 AWS

✅ Amazon EC2 - 확장 가능한 컴퓨팅 용량을 클라우드에서 제공하는 웹 서비스
✅ Amazon S3 - 확장성, 가용성, 내구성을 가진 데이터 저장 공간(Simple Storage)을 제공.
✅ Amazon RDS - 관계형 DB 관리 서비스. 관계형 DB(MySQL, Oracle 등)를 모니터링, 주기적 백업

  • on-Premise : 서버를 자체적으로 직접 운영
  • Serverless : 서버 작업을 서버내부가 아닌 클라우드 서비스로 처리, 클라우드 네이티브 개발모델 ex. AWS
  • Region : 데이터 센터가 물리적으로 존재하는 곳
  • CDN(Content Delivery Network) : 정적 리소스를 빠르게 제공할 수 있게 전세계의 캐시서버에 복제해주는 상호 연결된 서버 네트워크 서비스

🐣 원격 프로그램 실행

✅ 로컬 프로그램 실행
java.exe 자바인터프리터에서 Main에 있는 main()호출(static으로 설절하여 객체 선언없이 가능)

java Main

출력: Hello

public class Main{
	public static void main(String[] args){
    	Sysyem.out.println("Hello")

✅ 원격 프로그램 실행: 브라우저와 WAS
ip주소: 111.222.3333.444 + 톰캣포트: 8080 + context root: ch2 + URL: /Hello
ex. http://111.222.3333.444/8080/ch2/hello
❶ 프로그램 등록: 클래스 앞에 @Controller
❷ URL과 프로그램을 연결: 호출하려는 메서드에 @RequestMapping("/Hello") _ URL입력, 메서드 이름은 중요하지 않음

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

// 1. 원격 호출 가능한 프로그램으로 등록
@Controller 
public class Hello {
	int iv = 10; // 인스턴스 변수
	static int cv = 20; //static 변수
	
    // 2. URL과 메서드를 연결(맵핑)
	@RequestMapping 
	private void main() { //인스턴스 메서드 - iv, cv 둘다 가능
		System.out.println("Hello");
		System.out.println(cv); // ok
		System.out.println(iv); // ok
	}
	
	public static void main2() { //static 메서드 - cv만 가능
		System.out.println(cv); // ok
//		System.out.println(iv); // error
	}
  • Reflection API: 클래스 정보를 얻고 다를 수 있는 강력한 기능 제공
    ✔️ java.lng.reflect패키지 제공
public class Main {
	public static void main(String[] args) throws Exception {
//		hello.hello = new Hello();
//		Hello.main2(); //private이라서 외부 호출 불가

		//Hello클래스의 Class객체(클래싀 정보를 답고 있는 객체)를 얻어옴
		Class helloClass = Class.forName("com.fastcampus.ch2.Hello");
		Hello hello = (Hello)helloClass.newInstance();
		Method main = helloClass.getDeclaredMethod("main");
		main.setAccessible(true); //private인 main()을 호출가능하게 함
		
		main.invoke(hello); //hello.main()
	}

🐣 HTTP 요청과 응답

HttpServletResponse response

request.getCharacterEncoding()=null //요청내용
request.getContentLength()=-1 //요청 내용 길이(알수 없을 때 -1)
request.getContentType()=null //요청 내용 타입(null)

request.getMethod()=GET //요청방법
request.getProtocol()=HTTP/1.1 //프로토콜 종류와 버전
request.getScheme()=http //프로토콜

request.getServerName()=localhost //서버 이름 또는 ip 주소
request.getServerPort()=8080 //서버포트
request.getRequestURL()=http://localhost :8080/ch2/RequestInfo //요청 URL
request.getRequestURI()=/ch2/RequestInfo //요청 URI

request.getContextPath()=/ch2 //context path
request.getServletPath()=/RequestInfo //servlet path
request.getQueryString()=null //쿼리 스트링

request.getLocalName()=0:0:0:0:0:0:0:1 //로컬 이름
request.getLocalPort()=8080 //로컬 포트

request.getRemoteAddr()=0:0:0:0:0:0:0:1 //원격 ip주소(aws로 export연결하면 뜸)
request.getRemoteHost()=0:0:0:0:0:0:0:1 //원격 호스트 또는 ip주소
request.getRemotePort()=49344 //원격 포트

Example

http://localhost:8080/ch2/getYoil?year=2023&month=5&day=25

2023년 5월 25일은 목요일입니다.

//년원일을 입력하면 요일을 알려주는 프로그램
@Controller
public class YoilTeller {
	@RequestMapping("/getYoil")
	public void main(HttpServletRequest request, HttpServletResponse response) 
			throws IOException{
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String day = request.getParameter("day");
		
		int yyyy = Integer.parseInt(year);
		int mm = Integer.parseInt(month);
		int dd = Integer.parseInt(day);
		
		Calendar cal = Calendar.getInstance();
		cal.set(yyyy, mm-1, dd);
		
		int datOfWeek = cal.get(Calendar.DAY_OF_WEEK); //1:일요일, 2:월요일 ...
		char yoil = " 일월화수목금토".charAt(datOfWeek);
		
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");	
		
		PrintWriter out = response.getWriter();//response객체에서 브라우저로의 출력 스트림을 얻음	
		out.println(year + "년 " + month + "월 "+ day + "일은 ");
		out.println(yoil + "요일입니다.");
	}

}

  • QueryString: '?' 뒤에 매개변수 전달
    ex. String year = request.getParameter("year");
    ✅ Iterator: Enumeration enum = request.getParameterNames();
    ✅ key/value를 map(표)형식으로 반환: Map paramMap = request.getParameterMap();
    ✅ 같은 name, 여러 value: ?year=2021&year=2022&year=2023
    String[] yearArr = request.getParameterValues("year");
  • 리소스(resource)
    ✅ 동적 리소스: 스트리밍 등과 같이 프로그램 실행 시 마다 결과가 변하는 리소스, 웹서버 위에 떠있는 앱서버에 저장
    ✅ 정적 리소스: 이미지, js, css, html 등과 같이 파일 형태로 되어있어 변하지 않은 리소스

프로토콜

컴퓨터 내부에서, 또는 컴퓨터 사이에서 서로 교활할 데이터에 대한 형식을 정의하는 규칙 체계
HTTP(Hyper Text Transfer Protocol):
✔️ 텍스트 기반 프로토콜
✔️ 단순하고 읽기 쉬움
상태를 유지하지 않음(stateless) 클라이언트 정보 저장x
(쿠키와 세션을 사용하여 보완)
✔️ 확장 가능
커스텀 헤더 추가 가능

✅ HTTP 요청 메시지: 요청 메소드 GET, POST

✴️ GET: 서버의 리소스를 가져오기 위해 설계 READ / Query Stinrg을 통헤 데이터 전달(소용량)
URL에 데이터 노출되므로 보안취약 / 데이터 공유(전달)에 유리
ex. 검색엔진에서 검색단어 전송에 이용
✴️ POST: 서버에 데이터를 올리기 위해 설계 WRITE / 전송데이터 크기에 제한없음(대용량)
데이터를 요청메시지의 body에 담아 전송 / 보안에 유리(HTTP+TLS), 데이터 공유에는 불리
ex. 게시판에 글쓰기, 로그인, 회원가입

✅ HTTP 응답 메시지


텍스트파일/바이너리 파일

✅ 바이너리 파일: 문자 + 숫자, 데이터를 있는 그대로 읽고 씀
✅ 텍스트 파일: 문자, 숫자를 문자로 변환 후 씀

MIME(Multipurpose Internet Mail Extensions)

텍스트 기반 프로토콜에 바이너리 데이터 전송을 하기위해 고안된 HTTP의 Content-Type헤더에 사용, 데이터 타입에 명시
ex. response.setContentType("text/html");

Base64

✔️ '0'~'9','A'~'Z','a'~'z','+'.'/'
✔️ 64개 6bit
✔️ 바이너리 텍스트를 텍스트 데이터로 변환할 때 사용


🐣 클라이언트와 서버

servlet은 매개변수를 무조건 적어줘야 하지만 spring은 필요한 매개변수만 적어줘도 ok

✔️ 클라이언트: 서비스를 요청하는 애플리케이션/컴퓨터
✔️ 서버: 서비스를 제공하는 애플리케이션/컴퓨터
✔️ 역할에 따라 구분

서버: 제공 서비스 종류에 따라 구분
ex. Email server, File server, Web server

port:
✔️ 0~1023 예약됨
✔️ 한 대의 pc에 여러개의 서버가 존재하면 ip주소만으로 구분할 수 없음->port번호로 구분
✔️ 한 port에는 1개의 서버만 연결 가능
ex. 111.22.33.44:80 웹서버
✔️ binding: 주소 할당
✔️ listening: 연결요청 대기

WAS(Web Application Server): 프로그램을 서비스

브라우저 요청 → Tomcat server → Host → Context → Servlet(DispathcerServlet) → Contoller main() → 결과값 응답


🐣 설정파일 - server.xml, web.xml

톰캣설치경로/conf/server.xml: Tomcat 서버 설정
톰캣설치경로/conf/web.xml: Tomcat의 모든 web app 공통 설정
웹앱이름/WEB-INF/web.xml: web app 개별 설정
(sts: project명/src/main/webapp/WEB-INF/web.xml)

✅ 서블릿 등록: < servlet>...< /sevlet> @controller
✅ URL 연결: < servlet-mapping>...< /servlet-mapping> @RequestMapping("/서블릿주소")


참고) 자바의 정석 | 남궁성과 끝까지 간다

0개의 댓글