본문 바로가기
[패스트캠퍼스] Spring/스프링의 정석 : 남궁성과 끝까지 간다

CH.02 Spring MVC (01~04)

by 엑츄얼리 2022. 4. 27.

01. 원격 프로그램 실행 

1. 로컬 프로그램 실행(cmd)

> java Main

 java : java.exe (인터프리터)

 Main : Class 이름, Static이므로 실행 가능, Static이 아니면 객체를 생성해야 실행 가능

 

 

2. 원격 프로그램 실행

브라우저에 WAS의 URL 입력 시 실행 가능 (브라우저와 WAS(Tomcat)가 있어야 실행 가능)

웹에서 브라우저로 Server에 있는 프로그램 실행 시

 1. 프로그램 등록 (war 생성 및 배포)

 2. URL과 프로그램 연결

 

package com.spring.fastcampus.controller;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args)
            throws ClassNotFoundException, InstantiationException,
            IllegalAccessException, NoSuchMethodException, InvocationTargetException {
//        Hello hello = new Hello();
//        hello.main();//private라서 외부 호출 불가

        //Reflection API를 사용 - 클래스 정보를 얻고 다룰 수 있는 강력한 기능 제공
        //java.lang.reflect패키지를 제공
        //Hello클래스의 Class객체(클래스의 정보를 담고 있는 객체)를 얻어 온다.
        Class helloClass = Class.forName("ctx.Controller.Hello");
        Hello hello = (Hello)helloClass.newInstance();
        Method main = helloClass.getDeclaredMethod("main");
        main.setAccessible(true); //private인 main()을 호출가능하게 한다.

        main.invoke(hello);//hello.main();
    }
}

<Main.java>

 

package com.spring.fastcampus.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;

//1. 원격 호출가능한 프로그램으로 등록
@Controller
public class Hello {
    //2. URL과 메서드를 연결
    @RequestMapping(value="/hello")

  private String main(){
        System.out.println("Hello")
        return "index";
    }
}

<Hello.java>

 

Hello.java 에서 main 메서드

 1. private 더라도 tomcat이 reflection api를 통해 객체를 생성하기 때문에

     Controller가 접근 가능

 2. static이 아닌 Instance Method이므로 객체가 생성되어 있어야 실행 가능 => tomcat이 객체를 생성

 

 


02. AWS에 배포하기

Intellij에서 war 배포

 1. Project Structure -> Artifacts -> Add -> Web Aplication:Archive -> For '{프로젝트명}:war exploded -> Apply

 

 2. Build -> Build Artifact -> {프로젝트명}:war -> 프로젝트 폴더/out/Artifacts에 생성( {프로젝트명}_war.war )

 

 3. EC2 Instance에 원격으로 접속 -> tomcat9 Directory/webapps에 생성한 war파일을 복사

    * webapps : web에서 사용되는 application들이 저장되는 위치

 

 4. tomcat Directory/bin/startup.bat 실행 -> war파일을 자동으로 압축 해제 (외부에서 접근 가능)

    -> Local 브라우저에서 EC2 Instance의 Public IPv4 Address/{프로젝트명}_war/hello => 외부에서 실행 완료!

 

 


03. Http응답과 요청 - 실습

package com.spring.fastcampus.controller;

import java.util.Calendar;

//연월일을 입력시 요일을 알려주는 프로그램
public class YoilTeller {
    public static void main(String[] args) {
        //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 + "요일입니다.");
    }
}

<YoilTeller.java>

 

* cmd를 통해 Java Class 직접 실행

 a. Maven

    프로젝트 내부의 target 폴더 -> Open in -> Terminal

    cmd ->

> cd classes
> java Controller.YoilTeller 2022 04 23

 

 b. Gradle

    프로젝트 내부의 build 폴더 -> Open in -> Terminal

    cmd ->

> cd java/main
> java com.spring.fastcampus.Controller.YoilTeller 2022 04 23

 

 Maven, Gradle 둘다 정확한 디렉토리에서 Java Intepreter를 실행해야 Class파일을 실행하더라...

 

 

1. HttpServletRequest

...
@Controller
public class RequestInfo{
	@RequestMapping("/requestInfo")
    public void main(HttpServletRequest request){
    	request.getMethod();
    }
}

 HttpServletRequest (Interface) : 브라우저를 통해 요청 시, 요청을 request 객체에 담아 준다. (String[] args와 같은 원리)

 

 

2. HttpServletRequest 메서드

 *Spring MVC External Libraries 추가 방법

  Project Structure -> Modules -> Dependencies -> Add ... -> Apply

 

package com.spring.fastcampus.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;

//연월일을 입력시 요일을 알려주는 프로그램
@Controller
public class YoilTeller_remote {

    @RequestMapping("/getYoil")
    public static void main(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //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 + "요일입니다.");

        System.out.println(year + "년 " + month + "월 " + day + "일은 ");
        System.out.println(yoil + "요일입니다.");
    }
}

<YoilTeller_remote.java>

 

Chrome URL : localhost:8080/getYoil?year=2022&month=04&day=23

 

 * WEB-INF/dispatcher-servlet.xmp에서

   context:component-scan을 통해 Controller 폴더 위치 지정 가능

   + view 폴더 위치와 prefix, suffix 지정 가능

 

 


04. Http 요청과 응답

 리소스

  a. 동적 리소스 : 실행할 때마다 결과가 변함

  b. 정적 리소스 : img, CSS, HTML 등과 같이 고정된 정보를 갖고 있음

 

클라이언트 : 서비스를 요청하는 Application

서버         : 서비스를 제공하는 Application

 

 * Dispatcher-servlet

   Http프로토콜로 들어오는 모든 요청을 가장 먼저 받아 적합한 Controller에게 위임해주는 Front-Controller

 

 * WEB-INF 하위의 resources 폴더를 통해 정적 자원을 받아올 수 있음

댓글