우보천리 개발
Spring01 - @Controller, @RequestMapping, HttpServletRequest and Response 본문
Spring01 - @Controller, @RequestMapping, HttpServletRequest and Response
밥은답 2023. 12. 7. 22:21패스트캠퍼스 '스프링의 정석 - 남궁성과 끝까지 간다'를 들으며 정리한 내용
더 많은 내용을 배운다면 더 업데이트
현재는 입문자...
원격 프로그램 실행
원격에서 프로그램 실행하기 위해서는 1. 프로그램을 등록 2. URL과 연결하여 메소드 호출 할 수 있게 해줘야한다
@Controller 애너테이션을 통해서 프로그램을 원격 호출 할 수 있도록 등록한다.
@RequestMapping은 메소드를 연결해서 호출할 수 있도록 한다.
Java에서 static이 아닌 메소드는 객체 생성 없이 사용할 수 없는데 @RequestMapping이 붙은 메소드는 static이 안붙어도 호출이 된다
그 이유는 Tomcat 내부에서 객체를 생성해주기 때문이다
@RequestMapping("/hello")
private void main() {
System.out.println("HELLO");
}
메소드가 private임에도 불구하고 호출이 가능한 이유는 Spring은 Reflection API를 사용해서 객체를 생성한다
- Reflection API를 통해서 호출해보기
public class PrivateMethodCall {
public static void main(String[] args) throws Exception {
// Hello hello = new Hello();
// hello.main(); 호출 불가 - private
// 그렇다면 Hello.java 에서 private인 메소드는 어떻게 호출되었느냐
// Reflection API 를 통해서 클래스 정보를 얻어옴
// Reflection API로 불러오기
Class helloClass = Class.forName("com.firstSpring.app.Hello"); // 클래스 정보 얻어오기
Hello hello = (Hello)helloClass.newInstance(); // 반환 타입이 Object임 -> 형변환 필요
Method mainMethod = helloClass.getDeclaredMethod("main"); // 클래스의 메소드 가져오기
mainMethod.setAccessible(true); // private main()을 호출가능하게
// 실제로 호출하기
mainMethod.invoke(hello); // hello.main();
}
}
클래스의 정보를 모두 가져와서 private한 메소드도 호출 할 수 있다.
HttpServletRequest & HttpServletResponse
Client가 Server로 Request를 보낼 때 추가적인 정보를 보낼 수 있다.
http://localhost:8080/app/getYoil?year=2021&month=12&day=21
? 이후로 나오는 문자열은 요청하는 정보를 담은 객체를 생성하고 메소드의 매개변수로 전달하는 것이 HttpServletRequest 이다.
QueryString이라는 문자열에 "year"은 변수명, = 뒤에 나오는 문자열이 값
해당 객체로 얻어온 변수를 사용할 수 있다.
즉 request.getParameter("변수명")
@RequestMapping("/getYoil")
public void main(HttpServletRequest request, HttpServletResponse response) throws Exception {
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);
}
반대로 Server이 정보를 담아서 보내줄때는 HttpServletResponse객체를 사용한다
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter(); // response객체에서 브라우저 출력스트림 얻기
out.println(year + "년 " + month + "월 " + day + "일 =");
out.println(yoil + "요일");
response객체를 통해 해당 정보가 html형식, 인코딩 형식은 utf-8이라고 알려준다.
이후 getWriter()를 통해서 브라우저의 출력 스트림을 얻어서 브라우저에게 데이터 출력해준다