본문 바로가기

개발/Spring

스프링 애너테이션(Annotation)

728x90
반응형
애너테이션

 

스프링 3.0 부터는 DI 같은 자바 코드와 관련된 설정은 직접 코드에서 할 수 있게 애너테이션(Annotation) 이라는 기능을 제공합니다.

스프링에서 애너테이션을 사용하려면 스프링에서 제공하는 애너테이션 관련 클래스를 XML 설정 파일에서 빈으로 설정해야 합니다.

 

클래스 기능
DefaultAnnotationHandlerMapping 클래스 레벨에서 @RequestMapping 을 처리합니다.
AnnotationMethodHandlerAdapter 메서드 레벨에서 @RequestMapping 을 처리합니다.

 

 

 

<context:component-scan> 

 

<context:component-scan> 태그를 사용해 패키지 이름을 지정하면 애플리케이션 실행 시 해당 패키지에서 애너테이션으로 지정된 클래스를 빈으로 만들어 줍니다.

 

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

 

애너테이션 기능
@Controller 지정한 클래스를 컨트롤러의 빈으로 자동 변환
@Service 지정한 클래스를 서비스 빈으로 자동 변환
@Repository 지정한 클래스를 DAO 빈으로 자동 변환
@Component 지정한 클래스를 빈으로 자동 변환

 

 

[ WEB-INF/servlet.xml ]

 

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/test/" />
		
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 클래스 레벨의 @RequestMapping 을 처리 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
	<!-- 메서드 레벨의 @RequestMapping 을 처리 -->
	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<!-- base-package 에 존재하는 클래스에 애너테이션이 적용되도록 설정(하위 패키지 포함) -->
	<context:component-scan base-package="com.spring" />
</beans>

 

 

[ com.spring/Controller.java ]

 

package com.spring;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

// @Controller 애너테이션을 이용해 클래스를 빈으로 자동 변환(id = mainController)
@Controller("mainController")
// @RequestMapping 을 이용해 클래스 레벨의 요청 처리
@RequestMapping("/test")
public class MainController {
	// @RequestMapping 을 이용해 메서드 레벨의 요청 처리(Get)
	@RequestMapping(value = "/main1.do", method = RequestMethod.GET)
	public ModelAndView main1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("msg", "main1");
		mav.setViewName("main");
		return mav;
	}
	// @RequestMapping 을 이용해 메서드 레벨의 요청 처리(Post)
	@RequestMapping(value = "/main2.do", method = RequestMethod.POST)
	public ModelAndView main2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ModelAndView mav = new ModelAndView();
		mav.addObject("msg", "main2");
		mav.setViewName("main");
		return mav;
	}
}

 

 

 

@RequestParam

 

RequestParam 을 이용해 전송받은 매개변수를 설정한 후 브라우저에서 매개변수를 전달하면 지정한 변수에 자동으로 값이 설정됩니다.

 

...
	// @RequestParam 을 이용해 매개변수를 자동설정
	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();
		mav.setViewName("result");
		
		// getParameter 필요없이 값을 할당
		System.out.println("userID: "+userID);
		System.out.println("userName: "+userName);
...

 

required 속성을 설정할 수 있는데 기본값은 true 입니다.

true 로 설정했을때 메서드 호출 시 매개변수가 없으면 에러를 발생하지만 false 로 설정했을때 매개변수가 없으면 null 을 할당합니다.

 

public ModelAndView login(@RequestParam("userID", required = false) String userID, ...

 

@RequestParam 으로 Map 등의 매개변수 타입도 전송할 수 있습니다.

 

 

 

 

@ModelAttribute

 

객체에 값을 자동으로 할당해줍니다.

만약에 login 에서 userID 와 passwd 가 전달된 경우 자동으로 VO 클래스인 LoginVO 객체의 속성에 매개변수 값이 자동으로 설정됩니다.

 

...
@RequestMapping(value = "/login.do", method = { RequestMethod.GET, RequestMethod.POST })
// @ModelAttribute 를 이용해 전달되는 매개변수 값을 LoginVO 클래스와 이름이 같은 속성에 자동으로 설정
// add.. 등의 메서드 필요 없이 info 를 이용해 바로 JSP 에서 LoginVO 속성에 접근 가능
public ModelAndView login(@ModelAttribute("info") LoginVO loginVO,
                           HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("utf-8");

    System.out.println("userID: "+loginVO.getUserID());
    System.out.println("userName: "+loginVO.getUserName());
...

 

 

 

Model

 

Model 클래스를 이용하면 메서드 호출 시 JSP 로 값을 바로 바인딩하여 전달할 수 있습니다.

Model 클래스의 addAttribute() 메서드는 ModelAndView 의 addObject() 메서드와 같은 기능을 합니다.

Model 클래스는 따로 뷰 정보를 전달할 필요가 없을 때 사용하면 편리합니다.

 

...

@RequestMapping(value = "/test/login.do", method = { RequestMethod.GET, RequestMethod.POST })
// 메서드 호출 시 Model 클래스 객체 생성
public String login(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    request.setCharacterEncoding("utf-8");
	// JSP 에 전달할 데이터를 model 의 addAttribute 메서드를 이용해 바인딩
    model.addAttribute("userID", "kim");
    model.addAttribute("userName", "김철수");
    return "result";
}

 

JSP 에서는 ${userID}, ${userName} 으로 값을 출력할 수 있습니다.

 

 

여기까지 임미다.

728x90