-
Spring 프로젝트 파일 살펴보기궁금했던 것들/Spring 2019. 10. 23. 14:26
이전 포스팅에서는 대략적인 구조만 알아봤는데 이번에는 기본으로 생성되어있는 파일들에 대해 알아 보겠습니다.
============================================================================
1. HomeController
Controller 클래스는 요청이 오면 누가 처리애햐아는지를 분기처리해주고 그에 대한 결과값을 리턴해주는 클래스입니다.
1234567891011121314151617181920212223@Controllerpublic 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";}}cs 1) @Controller
제일 상단에 보면 @Controller 라고 적혀 있는데 이것이 어노테이션입니다.
자바로 이전에 개발해보셨분이라면 @Override를 사용해본적이 있을것입니다. 그것과 비슷하게 스프링 프레임워크에서도 컴파일러에게 정보를 주기위해 사용합니다.
어노테이션에 대해서는 따로 다음에 포스팅하겠습니다. 혹시 더 궁금하거나 다른 종류의 어노테이션을 알고 싶으면 "스프링 어노테이션 종류" 이런식으로 검색하면 글이 많습니다...
2) private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
두번째는 Logger 가 선언 되어있습니다. System.out.println(); 을 사용하지않고 Logger 객체를 사용해서 로그를 찍습니다. 로그에 대해서도 다음에 포스팅 하겠습니다.
3) @RequestMapping(value ="/", method = RequestMethod.GET)
요청이 오면 Dispatcher 역활을 하는 Controller 가 요청을 받고 그뒤에 @RequestMapping의 Value 값과 같은것을 찾습니다. 그리고 같은 것에게 요청을 넘겨서 처리하게됩니다.
그래서 처음에 서버를 켜고 아무것도 적지않은 localhost:8080/ 을 호출 했을때 home.jsp 가 나온이유입니다.
value 로 매핑되는 값을 적고 method로 GET, POST 방식을 정합니다.
method를 생략하게 되면 기본적으로 POST 방식이기 때문에 GET방식이 아니고서는 기본적으로 생략합니다.
4) model.addAttribute("serverTime", formattedDate );
model이라는 객체 안에 현재 시간을 String 형식으로 만든 formattedDate 를 addAttribute라는 메소드를 사용해서 serverTime 이라는 값과 매핑 해서 값을 추가했습니다.
Model 이라는 객체는 Controller에서 생성한 데이터를 담아서 View로 전달할 때 사용하는 객체 입니다.
따라서 View 부분인 jsp 파일에서 Model에서 추가한 값을 사용할수 있습니다.
Home.jsp 파일을 볼때 확인할것입니다.
5) return "home";
언뜻보면 String 값인 "home" 을 리턴했는데 어떻게 home.jsp 파일이 켜지는지 궁금해야하는게 당연합니다.
src/main/webapp/WEB-INF/spring/appServelt/servlet-context.xml 파일을 열어봅니다.
12345<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean>cs 이런 부분이 있을텐데 주석을 읽어보시면 컨트롤러가 렌더링하기위해 선택한 뷰를 /WEB-INF/views 폴더안의 .jsp로 해결합니다 이런뜻이고 아래의 property를 보면
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
즉. 리턴값 앞에 prefix인 /WEB-INF/views/ 을 추가하고 뒤에는 suffix인 .jsp를 추가해주겠다는것입니다.
그래서 그냥 "home" 을 반환 하더라도 "/WEB-INF/views/home.jsp" 이값이 반환되는것입니다.
2. log4j.xml
src/main/resources 아래에 있는 log4j.xml 입니다. log4j 라이브러리를 사용하기 위한 설정 파일입니다.
spring 프로젝트에서 사용하는 로그는 대표적으로 log4j, slf4j 이렇게 두가지 있습니다. 스프링 프로젝트를 처음 생성하면 기본으로 설정 되어있는것이 log4j 입니다.
https://inyl.github.io/programming/2017/05/05/slf4j.html를 들어가셔서 읽어보면 왜 slf4j가 더 좋은 것인지 나와있습니다. 그래서 slf4j로 바꿀것이기 때문에 파일의 내용은 자세히 보지 않겠습니다.
3. servlet-context.xml
12345678910111213141516171819202122<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --><resources mapping="/resources/**" location="/resources/" /><!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean><context:component-scan base-package="com.company.bokbok" /></beans:beans>cs 1) <annotation-drive/>
- @MVC 스타일의 컨트롤러에서 자주 사용되는 validator, conversionService, messageConverter를 자동으로 등록해주는 간편 빈 설정용 태그이다.
2) <resources mapping="/resources/**" location="/resources/" />
- jsp에서 이미지, 스크립트 등 경로를 통해 호출할때 resources 라고 선언된 경로들의 경로를 지정해주는것이다.
사용예는 <img src="<c:url value="/resources/img/javakingicon.jpg" />" width="250"/>
3) <context:component-scan base-package="com.company.bokbok" />
- 스프링이 검색할 패키지를 설정해주고 설정된 패키지에서 @Component 어노테이션이(또는 하위 어노테이션) 적용된 클래스를 검색하여 빈으로 자동등록 해줍니다.
1234@Component("service01")public class AbstractServiceImpl implements AbstractService {}이런식으로 클래스를 만들었다면 실제로는 <bean id="service01" class="service.AbstractServiceImpl"></bean> 과 같은 의미로 사용됩니다.
즉, 편리하게 빈을 등록 할 수있습니다.
4. root-context.xml
내용을 보면 아무것도 없는데 공통 빈을 설정 하는데 사용하라고 만들어지는것 같습니다.
5. home.jsp
1234567891011121314<%@ 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>Colored by Color Scripter여기서 볼것은 ${serverTime} 부분입니다. 이전에 controller 를 설명할때
model.addAttribute("serverTime", formattedDate ); 를 사용하여 모델 객체에 값을 담았는데 jsp에서 사용 할 수있다고 했습니다.
${serverTime} 이렇게 사용한다면 controller에서 넘겨줬던 값을 jsp에서 사용할수있습니다.
'궁금했던 것들 > Spring' 카테고리의 다른 글
Spring 프로젝트 구조 파악 (0) 2019.10.22 스프링 프로젝트 생성 (0) 2019.10.21 Spring 플러그인 설치 (0) 2019.10.21 Maven 설정 (0) 2019.10.17 Tomcat 설정 (0) 2019.10.16