Spring Framework

교과목 내용을 정리하기 위한 글입니다. 틀린 내용이 있을 수 있으니 참고하세요
MVC Pattern
스프링은 프레임워크는 MVC 아키텍쳐를 제공한다
- Model
데이터 캡슐화, POJO로 구성됨 - View
model 데이터를 랜더링, 대체로 HTML 형식 - Controller
사용자 요청 처리, 적절한 모델을 만들고 view 랜더링을 위해 넘겨줌
MVC 패턴
- Dispatcher Servlet
- 프론트 컨트롤러 역할
- 모든 요청을 가로채고 핸들러(컨트롤러)로 전달
- 요청을 처리할 컨트롤러를 호출하기 위해 핸들러 매핑을 참조
- Handler Mapping
- 특정 요청을 처리할 적합한 컨트롤러를 찾는 역할
- 요청 URL과 컨트롤러 클래스 간의 매핑은 XML 설정, 애노테이션을 통해 수행
- Controller
- 요청을 처리하며 비즈니스 로직 호출
- 출력은 모델 객체에 첨부되어 뷰로 전달
- View Resolver
- 논리적 이름으로부터 실제 뷰 파일을 찾는 역할
- View
- JSP, HTML ... 같은 실제 뷰 파일을 의미
Required Configuration
- Maven Configuration
POM.xml - Web deployment descriptor
Web.xml - Spring MVC Configuration
root-context.xml
,servlet-context.xml
,dao-context.xml
,service-context.xml
1. Maven Configuration
각종 라이브러리의 의존성 선언
POM.xml
2. Web deployment descriptor
DispatcherServlet
- Spring 컨테이너(WebApplicationContext) 인스턴스화
- 다른 DI 컨테이너와 마찬가지로, WebApplicationContext는 일부 구성 메타데이터를 제공받아야 함
DispatcherServlet
ContextLoadListener
- 공유 Beans가 포함된 Spring Container 인스턴스화
- DispatcherServlet에 의해 생성된 Beans은 ContextLoaderListener에 의해 생성된 Beans를 참조할 수 있음
(DispatcherServlet's Beans → ContextLoaderListener's Beans)
3. Spring MVC Configuration
root-context.xml
파일이 Spring 애플리케이션의 루트 컨테이너 설정을 담당하며, 기본적으로 비어 있지만 애플리케이션 시작 시 자동(ContextLoaderListener
) 으로 로드된다servlet-context.xml
`DispatcherServlet에 의해 로딩됨<annotation-driven />
프레임워크에 패키지 내 파일 스캔을 annotation based로 수행할 것임을 알림<resources mapping=… />
정적 메소드는 GET 요청으로 바로 접근할 수 있도록 매핑- Bean
InternalResourceViewResolver
물리 JSP 파일들을 논리 이름으로 어떻게 찾을 수 있는지 알려줌 <context:component-scan …/>
Spring Container에게 annotation based 사용시 어떤 패키지가 스캔될지 알려줌
Model
모델은 결과의 일부를 포함하며 객체를 컨트롤로에서 뷰로 전달할 때 사용된다. 이는 명명된 객체의 모음이다.
Key(name) | Value |
---|---|
key1 | value1 |
key2 | value2 |
key3 | value3 |
각 행은 named object 혹은 model attributes 로 불림
Model
모델 구현 방법은 세 가지로 나눌 수 있다.
1. Map
java.util.Map
public String getGreeting(Map<String, Object> model) {
String greeting = service.getRandomGreeting();
model.put("greeting", greeting);
...
}
2. Model
Spring 에서 제공하는 Model interface 구현하여 사용된다
- Model에서는 key 값을 지정해줄 필요가 없음
- 모델을 채우기 위한 편리한 방법 제공됨 (addAttribute())
- key 값을 자동 혹은 수동으로 지정할 수 있음
public String getGreeting(Model model) {
List<SpecialDial> specialDeals = service.getSpecialDeals();
model.addAttribute(specialDeals); // key 값 자동 (수동으로 지정도 가능)
}
3. ModelMap
Spring에서 제공되는 객체로 더 편리함을 제공 (chained calls)
public String getGreeting(ModelMap model) {
...
model.addAttribute(“name”, “Jon”)
.addAttribute(“surname”, “Snow”)
}
Controller
@Controller 어노테이션이 붙은 빈(bean)
- @Controller 어노테이션
컨트롤러 역할을 한다는 것을 나타냄 - @RequestMapping 어노테이션
URL ↔︎ 전체 클리스, 특정 핸들러 메소드 매핑
1. Class level mapping
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
...
}
2. Handler level mapping
@Controller
public class EmployeeController {
@RequestMapping("/employee-management/employees")
public String getAllEmployees(Model model){
return "employeesList";
}
}
3. Example
1. Add attributes to the model
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
...
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home"; // Logical view name
}
2. Retrieve request parameters as regular parameters
@RequestMapping(value="/login", method = RequestMethod.GET)
public String doLogin(@RequestParam String username,
@RequestParam String password) {
...
return success;
}
JSTL
- JSP는 Java Server Pages의 약자로, 동적인 웹 페이지를 생성하는 데 사용되는 기술
- prefix “c” can be used for core language
- prefix “fn” for using JSTL functions
<?xml version="1.0" encoding="UTF-8" ?>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<c:forEach var="i" begin="0" end="5">
Item <c:out value="${i}"/><p>
</c:forEach>
<c:if test="${fn:length(friends) > 0}" >
<%@include file="welcome.jsp" %>
</c:if>