1. 개요
이 테크 노트는 신규로 생성한 스프링 프로젝트에 Controller를 추가하는 실습임
2. 사전작업
이클립스에서 Spring Project 를 만들어본다.
3. 신규 Controller 생성
3-1. HomeController 분석
우선 앞서 만든 스프링 프로젝트에 기본으로 포함되어 있는 HomeController를 살펴보자.
package com.test.myfirst;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
@RequestMapping(value = "/", method = RequestMethod.GET) 을 통해 / 에 해당하는 요청을 처리하는 Controller임을 알 수 있다.
그러면 우리는 새로운 URL을 처리하는 Controller를 추가해보기로 하겠다.
3-2. TimeController 생성
임의로 TimeController라는 것을 만들어보겠다. 새로 뭔가 만들기는 어려우니 위의 HomeController를 그대로 사용할 것이다.
TimeController.java는 src/main/java/com/test/myfirst 아래에 만든다. (com/test/myfirst는 앞선 장에서 내가 com.test.myfirst라는 패키지로 생성을 했기 때문이라는 것을.. 모르면.. 지금 안된다..)
그렇게 고친 것이 다음과 같다.
package com.test.myfirst;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class TimeController {
private static final Logger logger = LoggerFactory.getLogger(TimeController.class);
@RequestMapping(value = "/time.do", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome Time Controller! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
}
- 클래스 이름이 다르다. (TimeControll.java)
- RequestMapping이 다르다. /time.do 라는 요청을 처리하기 위하여 수정되었다.
- 로거 클래스가 HomeController에서 TimeController로 바뀌었다.
- 로거가 찍는 문자열이 "Welcome home!" 에서 "Welcome Time Controller!" 로 수정되었다.
4. 실행
이제 톰캣 서버를 다시 시작해보자. 그리고 http://localhost:8080/myfirst/time.do 를 호출하면..
아까 http://localhost:8080/myfirst/ 롤 호출한 것과 같은 결과를 볼 수 있다! (당연하다..) 우리는 단지 time.do가 호출이 되도록 처리만 했지 화면, 즉 view에 대한 것은 전혀 수정한 바가 없기 때문이다. 그러면 화면도 수정하고 싶다면?
HomeController든 TimeController든 리턴으로 넘겨주는 것은 아래와 같다.
return "home";
home. 이것은 src/main/webapps/views 아래의 home.jsp를 뜻한다.
5. View
5-1. home.jsp
src/main/webapps/views/home.jsp 파일을 보자.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
/ 이든 /time.do 든 우리가 보았던 화면이 바로 이 파일이다.
그리고 ${serverTime}은 우리가 Controller에서 넘겼던 아래 값과 매핑되는 것이다.
model.addAttribute("serverTime", formattedDate );
5-2. time.jsp
그러면 /time.do에 대한 새로운 뷰를 만들어보자. 위치는 일단 home.jsp가 있는 src/main/webapps/views 아래에 만들면 되겠다. 즉, src/main/webapps/views/time.jsp이다.
많은 내용을 고칠 것은 없고 문구만 바꿔보자.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Time</title>
</head>
<body>
<h1>
Hello time!
</h1>
<P> The time on the server is ${serverTime}. </P>
</body>
</html>
추가로 할 일이 있다. TimeController에서 time.jsp로 리턴하도록 수정하는 것이다.
return "time";
이제 /time.do 호출 시 바뀐 문구를 확인할 수 있다!