웹사이트 검색

스프링 컨트롤러 - 스프링 MVC 컨트롤러


Spring Controller 어노테이션은 @Component 어노테이션의 특수화입니다. Spring Controller 어노테이션은 일반적으로 RequestMapping 어노테이션을 기반으로 어노테이션이 있는 핸들러 메소드와 함께 사용됩니다.

스프링 컨트롤러

Spring Controller 어노테이션은 클래스에만 적용할 수 있습니다. 클래스를 웹 요청 처리기로 표시하는 데 사용됩니다. 주로 Spring MVC 애플리케이션과 함께 사용됩니다.

스프링 레스트 컨트롤러

Spring RESTful 웹 서비스.

스프링 컨트롤러 예제

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-webmvc</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-web</artifactId>
	<version>5.0.7.RELEASE</version>
</dependency>

<!-- Jackson for REST -->
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.9.6</version>
</dependency>

DispatcherServlet 서블릿을 전면 컨트롤러로 구성할 배포 설명자(web.xml)를 살펴보겠습니다.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" 
 xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Spring-Controller</display-name>
  <!-- Add Spring MVC DispatcherServlet as front controller -->
	<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
       		<param-name>contextConfigLocation</param-name>
       		<param-value>/WEB-INF/spring-servlet.xml</param-value>
    		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern> 
    </servlet-mapping>
</web-app>

마지막으로 다음과 같은 스프링 컨텍스트 파일이 있습니다. 여기에서 애플리케이션을 주석 기반으로 구성하고 스프링 구성 요소를 스캔하기 위한 루트 패키지를 제공합니다. 또한 InternalResourceViewResolver 빈을 구성하고 뷰 페이지의 세부 정보를 제공하고 있습니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<context:component-scan base-package="com.journaldev.spring" />

	<!-- 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>

</beans:beans>

구성 XML 파일이 준비되었습니다. 이제 Controller 클래스로 이동하겠습니다.

package com.journaldev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

	@GetMapping("/hello")
	public String home(Locale locale, Model model) {
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		String formattedDate = dateFormat.format(date);
		model.addAttribute("serverTime", formattedDate);
		return "home";
	}

}

우리는 단일 요청 처리기 메서드를 정의했습니다. URI가 "/hello”인 GET 요청을 수락하고 응답으로 "home.jsp” 페이지를 반환합니다. home.jsp 페이지에서 사용될 모델에 대한 속성을 설정하고 있음을 주목하십시오. 다음은 간단한 home.jsp 페이지 코드입니다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
	<h1>Hello world!</h1>

	<p>The time on the server is ${serverTime}.</p>

</body>
</html>

스프링 MVC 컨트롤러 테스트

Spring RestController 예제

이제 애플리케이션을 확장하여 REST API도 노출해 보겠습니다. JSON 응답으로 보낼 모델 클래스를 만듭니다.

package com.journaldev.spring.model;

public class Person {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

다음은 간단한 REST 컨트롤러 클래스입니다.

package com.journaldev.spring.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.journaldev.spring.model.Person;

@RestController
public class PersonRESTController {

	@RequestMapping("/rest")
	public String healthCheck() {
		return "OK";
	}

	@RequestMapping("/rest/person/get")
	public Person getPerson(@RequestParam(name = "name", required = false, defaultValue = "Unknown") String name) {
		Person person = new Person();
		person.setName(name);
		return person;
	}

}

애플리케이션을 다시 배포하여 REST API를 테스트합니다.

스프링 REST 컨트롤러 테스트

요약

Spring Controller는 Spring MVC 애플리케이션의 근간입니다. 이것이 우리의 비즈니스 논리가 시작되는 곳입니다. 또한 RestController는 나머지 기반 웹 서비스를 쉽게 만들 수 있도록 도와줍니다.

GitHub 리포지토리에서 예제 프로젝트 코드를 다운로드할 수 있습니다.