본문 바로가기

백엔드 개발/SpringMVC

HTTP 요청과 응답 (예제)

1.  브라우저 새로 고침 할 때마다 랜덤 주사위가 나오는 예제 

package com.fastcampus.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;

// 해당 자바 클래스를 컨트롤러로 등록 
// 컨트롤러로 등록하면, 브라우저(view)에서 어떤 요청이 왔을 때, 
// 이 클래스의 내용(model)과 일치하면 이 클래스를 쓰겠다고 선언하는 것임.
// Controller는 view와 Model의 가교 역할

@Controller
public class Twodice {
	@RequestMapping("/rollDice")
    
    // reponse만 필요한 이유: 이번 경우에는 클라이언트가 요청 때 보낸 값들이 없기 때문에
	public void main (HttpServletResponse response) throws IOException {
		
        
		int indx1 = (int)(Math.random()*6)+1;
		int indx2 = (int)(Math.random()*6)+1;
		
        //해당 컨텐츠에 담긴 내용이 text인지 binary인지 컴퓨터에게 알려주는 것 
        // 여기선 text 중 html임을 알려줌. 
		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"+indx1+ ".jpg'>");
		out.println("<img src = 'resources/img/dice"+indx2+".jpg'>");
		out.println("</body>");
		out.println("</html>");
	}
}

** 참고 ** 

Math.random()은 double 형 반환 매소드 이고, 0.0~1.0 미만 사이의 특정 값을 반환하는 함수이다. 

int 로 형 변환 하면 뒤에 소수점 다 짤리고 *6하면  최대가 0.9xx*6이니까 5.4xxx이다. 

따라서 0~ 5가 나올 수 있고 여기다가 +1을 했으므로 1~6이 나올 수 있다. 

2. 이론 설명

hello가 요청 보내는 주소, @RequestMapping(/hello)로 요청과 그에 대한 서비스를 연결// 요청이 들어오면 서버는 그에 해당하는 서비스를 찾아서 html.txt 문서로 브라우저에 다시 보낸다.

(1) 리소스에 대하여

서버에서 제공하는 리소스에는 동적 리소스와 정적 리소스가 있다. 

동적 리소스는 실행할 때 마다 값이 바뀌는 프로그램, 라이브 방송(스트리밍) 같은 것이 있다. 

정적 리소스는 파일 형태로 되어 있어 바뀌지 않는 것 (이미지, js, css, html) 등이 있다. 

3. 스스로 해보기

package com.fastcampus.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 index1 = (int)(Math.random()*6) + 1;
		int index2 = (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" +index1+".jpg'>");
		out.println("<img src = 'resources/img/dice" +index2+".jpg'>");
		out.println("</body>");
		out.println("</html>");
	}
}

틀린 것 

@RequestMapping 다음에는 어떤 주소로 들어와야 이 클래스가 실행될 것인지 주소를 적어야한다.

 

 

< 2번째 스스로 해보기 23.03.31 >

이번에는 안보고 해보기 + jsp 페이지로 받아서 해보기 

안 보고 해볼려 했는데, 직접 치니까 오타가 나와 엄청 해맸다. .setContentType("text/html")인데 "txt/html"이라 적어서 

경로 접속 할 때마다 계속 이상한 파일이 다운 되었다. 다행히 카페에 물어서 내가 오타났음을 인지 했다. 

 

그리고 resources 폴더가 두 개인데, 내가 사용해야 하는 건 WebApp 아래에 있는 resources 폴더인데, 자꾸 최상단의 resources 폴더 써가지고 이미지를 못 찾았다. 

이 두부분에 막혀서 강의를 봤다. 

결국 성공했다. 

 

그리고 Jsp 페이지로 받아서 해보기 

model.addAttribute()에서 ()안에 map 형태로 <변수이름 ,값>으로 넣어줘야 한다는 것을 까먹었다. 

Jsp에서 해당 변수 깔 때는 ${} 대괄호 템플릿으로 한번 감싸야 한다. 이게 없으면 변수인지 check를 못해서 내용물이 아니라 변수 값 전체를 출력해버린다. 

 

js 처럼 ``이거 쓴 뒤에 ${} 해야하는지 알았는데 그게 아니었다. 그냥 "" 안에 ${}를 써주면 된다. 

dice${idx]라고 써줘야 하는데 둘 사이 공백을 둬서 또 에러가났다.

총 1시간 16분이 걸렸다.