개발/스프링

14. 스프링 프레임워크 - @어노테이션[자바웹을 다루는 기술]

괴발자-K 2022. 5. 23. 18:07

이전 장에서 DI, AOP 등을 XML에 설정하여 사용했습니다. 하지만 코드가 많아지고 복잡해지면 XML이 설정 파일이 

매우 복잡해졌습니다. 이런점을 보완하기 나온게 Annotation(@) 입니다. 어노테이션은 주석이라는 뜻을 가지고 있지만

스프링에서는 그 이상의 기능을 가지고 있습니다. @Controller, @Component, @Service, @Repository, @Bean 등 

여러가지 어노테이션을 스프링에서 자주 사용하고 있습니다.

스프링에서는 xml의 방식과 어노테이션의 방식을 혼합해서 사용하고 있습니다. 

스프링에서 자주 쓰이는 어노테이션 관련 클래스 및 기능에 대해 알아보겠습니다.

 

어노테이션 종류

어노테이션 기능
@Controller component-scan에 의해 지정한 클래스를 컨트롤러 빈으로 자동 변환
@Service component-scan에 의해 지정한 클래스를 서비스 빈으로 자동 변환
@Repository component-scan에 의해 지정한 클래스를 DAO 빈으로 자동 변환
@Component component-scan에 의해 지정한 클래스를 빈으로 자동 변환

 

1. web.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
	http://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 -->
	<mvc:annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory 
	     JSP에서 사용될 자바스크립트나 이미지 파일 경로를 저장-->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory 
	           뷰리졸버 빈을 생성하면서 응답할 JSP의 경로를 지정-->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/test" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<!--패키지와 애너테이션을 지정  -->
	<context:component-scan base-package="com.spring" />
	
</beans:beans>

<mvc:annotation-driven /> 를 설정하여 RequestMappingHandler 을 자동으로 설정해 줍니다. 

<context:component-scan base-package="패키지 이름" />

애플리케이션 실행 시 해당 패키지에서 애너테이션으로 지정된 클래스를 빈으로 만들어 줍니다.

2. LoginController.java

package com.spring.ex02;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
   
	@RequestMapping(value= {"/test/loginForm.do", "/test/loginForm2.do"}, method = RequestMethod.GET)
	public ModelAndView loginForm(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView();
		mav.setViewName("loginForm");
		return mav;
	}

	//@RequestParam을 이용해 받을 값을 지정한 변수에 자동으로 설정
	@RequestMapping(value="/test/login.do", method= {RequestMethod.GET, RequestMethod.POST})
	public ModelAndView login(@RequestParam("userID") String userID, @RequestParam("userName") String userName,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("utf-8");
		ModelAndView mav = new ModelAndView();
		//String userID = request.getParameter("userID");
		//String userName = request.getParameter("userName");
		
		System.out.println("userID: " + userID);
		System.out.println("userName:" + userName);
		mav.addObject("userID", userID);
		mav.addObject("userName", userName);
		mav.setViewName("result");
		
		return mav;
		
	}
    
}

@RequestMapping()으로 요청 값 설정 및 GET, POST 방식을 설정 합니다.

@RequestParam을 통해 받아오는 값을 지정한 변수에 자동으로 설정 합니다.

 

 

간단하게 어노테이션을 통해 로그인 기능을 구현해봤습니다. 위와 같이 XML을 최소하여 코드를 좀더 간결하고 

가독성 있게 작성 할수 있었습니다.

 

#마무리

<mvc:annotation-driven /> 으로 간단하게 설정하였지만, xml 빈으로 handler와 adaptor를 설정하는 방법을 

찾아서 해보시는것을 추천 드립니다. 필자는 스프링 3.1 이전 버전으로 하여 deparated된 클래스로 진행 하였지만 

크게 다를게 없어 보입니다.