새로운 클래스 만들기

 

다이스 이미지파일 다운로드 후 src - main - webapp - resources 안에 붙여넣기

 

 

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 //ctrl + shift + o => 자동 import
public class TwoDice {
	@RequestMapping("/rollDice")
	public void main(HttpServletResponse response)throws IOException {
		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 = '/img/dice1.jpg'>");
		out.println("<img src = '/img/dice2.jpg'>");
		out.println("</body>");
		out.println("/html>");
	}

}

 

 

서버를 킨후 뒤에 /rollDice를 붙여 넣어준다.

 

이렇게 나올텐데 당황하지 말고 우클릭 후 페이지 소스보기

 

이번엔 검사를 했다.

경로가 잘못되어서 이미지가 나오지 않음.

경로를 바꾸어서 입력하였다.

 

코드에서 경로를 바꿔야 한다.

경로에 resources를 한번 타고 들어가야하기 때문에 resources/ 를 추가

 

 

Math.random() * 6은 0~5까지라서 + 1

이 때 중요한 것은 문자열을 어떻게 붙이는지 이다. + " aaaa" + 가 아닌 "+aa+" 이다.

 

이제 새로고침할때 마다 주사위의 숫자가 다르게 나온다.

 

프로그램의 진행 순서로를 보기 위해 16째줄 우클릭 후 브레이크 포인트(중단점)

 

run as 가 아닌 debug as로 접속을 하면 화면이 멈춰지고 디버깅 내용이 찍힌다.

 

 

Http프로세서가 요청을 받아 요청정보를 Request 객체 담아서 보낸다.

스레드에서 프로세서 엔진 그리고 컨텍스트로 진행 중을 볼 수 있다.

엔진안에 호스트 그 안에 컨텍스트가 있기 때문

그리고 디스패처 서블릿이 받는다.

컨트롤러로 이동

 

프로그램의 실행결과를 톰캣이 아닌 브라우저에 출력할 것이다.

년월일을 말하면 요일을 출력할 것이다.

 

새로운 클래스를 만든다.

 

package com.fastcampus.ch2;

import java.util.Calendar;

public class YoilTeller {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		// 1. 입력
		String year = args[0];
		String month =args[1];
		String day = args[2];
		
		int yyyy = Integer.parseInt(year); //문자열이니 숫자로 변경
		int mm = Integer.parseInt(month);
		int dd = Integer.parseInt(day);
		
		// 2. 작업
		Calendar cal = Calendar.getInstance(); //날짜 셋팅
		cal.set(yyyy, mm-1, dd);
		
		int dayOfweek = cal.get(Calendar.DAY_OF_WEEK); //1:일요일, 2:월요일 ...
		char yoil = " 일월화수목금토".charAt(dayOfweek); //다시 문자열로 변경
		
		// 3. 출력
		System.out.println(year + "년" + month + "월" + day + "일은");
		System.out.println(yoil + "요일입니다");
		
	}

}

 

 

매개변수로 받아야해서 콘솔에서 실행해야 한다.

cd classes

java com.fastcampus.ch2.YoilTeller 2024 10 29

입력하면 요일이 출력됨

 

 

 

 

package com.fastcampus.ch2;

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

import javax.servlet.http.HttpServletRequest;

@Controller
public class RequestInfo {
    @RequestMapping("/requestInfo")
    public void main(HttpServletRequest request) {
        System.out.println("request.getCharacterEncoding()="+request.getCharacterEncoding()); // 요청 내용의 인코딩
        System.out.println("request.getContentLength()="+request.getContentLength());  // 요청 내용의 길이. 알수 없을 때는 -1
        System.out.println("request.getContentType()="+request.getContentType()); // 요청 내용의 타입. 알 수 없을 때는 null

        System.out.println("request.getMethod()="+request.getMethod());      // 요청 방법
        System.out.println("request.getProtocol()="+request.getProtocol());  // 프로토콜의 종류와 버젼 HTTP/1.1
        System.out.println("request.getScheme()="+request.getScheme());      // 프로토콜

        System.out.println("request.getServerName()="+request.getServerName()); // 서버 이름 또는 ip주소
        System.out.println("request.getServerPort()="+request.getServerPort()); // 서버 포트
        System.out.println("request.getRequestURL()="+request.getRequestURL()); // 요청 URL
        System.out.println("request.getRequestURI()="+request.getRequestURI()); // 요청 URI

        System.out.println("request.getContextPath()="+request.getContextPath()); // context path
        System.out.println("request.getServletPath()="+request.getServletPath()); // servlet path
        System.out.println("request.getQueryString()="+request.getQueryString()); // 쿼리 스트링

        System.out.println("request.getLocalName()="+request.getLocalName()); // 로컬 이름
        System.out.println("request.getLocalPort()="+request.getLocalPort()); // 로컬 포트

        System.out.println("request.getRemoteAddr()="+request.getRemoteAddr()); // 원격 ip주소
        System.out.println("request.getRemoteHost()="+request.getRemoteHost()); // 원격 호스트 또는 ip주소
        System.out.println("request.getRemotePort()="+request.getRemotePort()); // 원격 포트
    }
}

 

서버를 실행해서 url에 검색했다.

 

Main클래스의 이름을 PrivateMethodCall로 변경

 

 

다시 YoilTeller 클래스에 들어가서 원격으로 request받기 위해 코드 수정

package com.fastcampus.ch2;

import java.util.Calendar;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class YoilTeller {
	@RequestMapping("/getYoil")
	public void main(HttpServletRequest request) {
		// TODO Auto-generated method stub
		
		// 1. 입력
		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);
		
		// 2. 작업
		Calendar cal = Calendar.getInstance(); //날짜 셋팅
		cal.set(yyyy, mm-1, dd);
		
		int dayOfweek = cal.get(Calendar.DAY_OF_WEEK); //1:일요일, 2:월요일 ...
		char yoil = " 일월화수목금토".charAt(dayOfweek); //다시 문자열로 변
		
		// 3. 출력
		System.out.println(year + "년" + month + "월" + day + "일은");
		System.out.println(yoil + "요일입니다");
		
	}

}

 

 

 

브라우저에 결과 나오기 위해 리스폰스 객체를 매개변수로 추가 해야한다.

 

또한 println으로 출력된 것을 브라우저로 맞춰서 변환 + 예외처리

 

package com.fastcampus.ch2;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

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 YoilTeller {
	@RequestMapping("/getYoil")
	public void main(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		
		// 1. 입력
		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);
		
		// 2. 작업
		Calendar cal = Calendar.getInstance(); //날짜 셋팅
		cal.set(yyyy, mm-1, dd);
		
		int dayOfweek = cal.get(Calendar.DAY_OF_WEEK); //1:일요일, 2:월요일 ...
		char yoil = " 일월화수목금토".charAt(dayOfweek); //다시 문자열로 변
		
		// 3. 출력
		response.setContentType("text/html");//텍스트 인지 알려주고
		response.setCharacterEncoding("utf-8"); //인코딩 방식을 알려주어야 한다.
		PrintWriter out = response.getWriter(); // response객체에서 브라우저로 출력 스트림을 얻는다.
		out.println(year + "년" + month + "월" + day + "일은");
		out.println(yoil + "요일입니다");
		
	}

}

 

utf-8로 인코딩 방식을 알려줌으로서 한글 깨짐 방지

 

다시 url 에 입력

같은 컴퓨터 안에 브라우저와 톰캣을 띄어봤으니

이제 본격적으로 AWS에 올려 볼 것이다.

 

그러기 위핸 우리가 만든 프로젝트를 export해야 한다.

 

war파일 선택 후

 

프로젝트이름과 경로를 저장하는데 이때 중요한 것은

확장자를 .war로 해야 한다.

압축파일로 만들어질 수도 있고 war자체로 만들어질 수 있는데 상관 없다.

 

 

 

 

aws에 들어가서 프리티어 서비스 사용량을 확인 할 수 있다.

오른쪽 상단에 본인 아이디 클릭 후 - 계정 - 프리티

인스턴스가 실행중이라면 사용하지 않을 경우 중지를 하자

 

원격을 다시 시작하려니 갑자기 만들었던 인스턴스가 보이지 않았다.

알고보니 지역선택이 바뀌어져 있으니 원래 지정했던 것으로 돌려놓으니 해결된다.

 

 

연결

 

 

중지했다 시작하면 ip가 바뀌므로 원격 데스크톱 다운로드를 다시 해주어야 한다.

 

기존의 만들었던 key를 가져오고 해독한 후 복붙

 

아까 만들었던 ch2.war 파일을 apache-tomcat - webapps에 복붙하면 자동으로 압축이 풀린다.

 

createshortcut 후 바탕화면으로 이동

 

실행을 하면 압축이 풀리면서 ch2 폴더가 만들어진다.

 

 

이제 로컬에서 원격 aws서버를 접속할 것인데

IPv4 퍼블릭 ip를 복사

 

로컬PC에서 localhost 대신 복사한 IPv4를 붙여 넣으면 이렇게 나오는데 

 

IPv4 + :8080/ch2/hello 하니 접속이 된 것을 확인할 수 있다.

+ Recent posts