"/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>");
}
}
📌 코드에서 thorws IOException 이 명시되어 있다면,
main() method에서는 IOException이 발생할 수도 있는 작업을 할 것이며,
만약에 발생한다면, 이를 처리하지 않고 main()을 부른(invoke) 곳으로
이 에러를 던진다는 의미이다
📌I/O 란?
Input과 Output의 약자로 입출력을 의미한다
입출력의 간단한 예로 키보드로 텍스트를 입력하고, 모니터로 입력한 텍스트를 출력하는 것
📌Math.random()
0 ~ 1사이의 난수를 무작위로 생성한다
❗ 서버가 제공하는 리소스는 두가지가 있다
✔ TwoDice.java 클래스 파일은 실행할 때마다 결과가 달라지는데 이런걸 동적 리소스 라고 한다 - 리소스 내용이 고정되지 않음
ex) 프로그램 / 스트리밍(Live) 등
✔ 반면에 img파일 같은 건 정적 리소스 라고 부른다
ex) .js / .css / .html 등