TIL | Spring HTTP 요청과 응답 예제

김윤희·2022년 8월 1일
0

HTTP 요청과 응답 예제


"/rollDice"를 요청하면 브라우저에서 동적으로 두개의 주사위가 랜덤으로 뜨도록 만들어보기

package com.campus.ch2;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class TwoDice {
	@RequestMapping("/rollDice")	//요청
	public void main(HttpServletResponse response) throws IOException{	// 응답
		int idx1 = (int)(Math.random()*6)+1; // double -> int 형변환
		int idx2 = (int)(Math.random()*6)+1;
		
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("</head>");
		out.println("<body>");
		out.println("<img src='resources/img/dice"+idx1 +".jpg'>");
		out.println("<img src='resources/img/dice"+idx2 +".jpg'>");
		out.println("<html>");
		out.println("</body>");
		out.println("</html>");
	}
}
  • 📌예외처리?
    • JVM은 프로그램에서 에러가 발생했을 때, Exception을 던지게(throw) 된다
      일반적으로, 이를 try - catch를 사용하여 프로그램에서는 처리한다
      하지만, 어떤 경우에서는 이를 다시 자신이 처리하지 않고 자신을 부른 곳으로 던지게 된다
      그럴 경우에는 method에 thows java.io.IOException과 같이 명시를 하게 된다
  • 📌 코드에서 thorws IOException 이 명시되어 있다면,
    main() method에서는 IOException이 발생할 수도 있는 작업을 할 것이며,
    만약에 발생한다면, 이를 처리하지 않고 main()을 부른(invoke) 곳으로
    이 에러를 던진다는 의미이다

    • 참고로, IOException은 input/output을 처리할 때 주로 발생한다
      예를 들어, 파일 처리 같은 경우이다
  • 📌I/O 란?
    Input과 Output의 약자로 입출력을 의미한다
    입출력의 간단한 예로 키보드로 텍스트를 입력하고, 모니터로 입력한 텍스트를 출력하는 것

  • 📌Math.random()
    0 ~ 1사이의 난수를 무작위로 생성한다

    • 난수의 범위 지정은 곱하기 * 기호와 더하기 + 기호로 최대값과 최소값을 지정할 수 있다
      • 난수의 범위 조절 [Math.random() * 최대값]
        곱하기 * 기호를 사용하면 된다
        왜냐하면 난수의 범위 시작이 0이므로 0에는 어떤 수를 곱해도 0이기 때문이다
        따라서 최대값인 1에만 원하는 최대 범위를 곱하면 된다

서버가 제공하는 리소스는 두가지가 있다
✔ TwoDice.java 클래스 파일은 실행할 때마다 결과가 달라지는데 이런걸 동적 리소스 라고 한다 - 리소스 내용이 고정되지 않음
ex) 프로그램 / 스트리밍(Live) 등
✔ 반면에 img파일 같은 건 정적 리소스 라고 부른다
ex) .js / .css / .html 등

0개의 댓글