Post

Spring 어노테이션, 컨트롤러 개념

Spring 어노테이션, 컨트롤러 개념

Spring - @Autowired

@Autowired는 필요한 의존 객체를 스프링이 자동으로 주입해준다.

1
2
@Autowired
private Chef chef;

Spring - @Component

@Component는 해당 클래스를 스프링이 관리하는 Bean으로 등록한다.

1
2
3
4
5
6
7
8
9
@Component
public class SampleHotel {
	private final Chef chef;

	@Autowired
	public SampleHotel(Chef chef) {
		this.chef = chef;
	}
}

이 어노테이션을 사용하려면 root-context.xml에 Bean 스캔을 설정해야 한다.

1
<context:component-scan base-package="패키지명"></context:component-scan>

그리고 root-context.xml의 아래쪽 NameSpaces 탭에서 context 항목을 체크해야 한다.


Spring - 세팅 방법

  1. 프로젝트 생성

    • Spring Legacy Project (Spring MVC Project)
  2. 서버 포트번호 설정

    • Servers 탭 > Tomcat 설정 더블클릭
    • Overview 탭에서 포트번호 변경
    • Modules 탭에서 Path를 /로 수정
  3. pom.xml 설정 변경

    • Java 버전: 1.611
    • Spring 버전: 3.1.1.RELEASE5.0.7.RELEASE
    • JUnit 버전:
    1
    2
    3
    4
    5
    6
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    
    • Log4j 버전:
    1
    2
    3
    4
    5
    
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    
    • Maven Compiler Plugin:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.5.1</version>
        <configuration>
            <source>11</source>
            <target>11</target>
            <compilerArgument>-Xlint:all</compilerArgument>
            <showWarnings>true</showWarnings>
            <showDeprecation>true</showDeprecation>
        </configuration>
    </plugin>
    

Spring - Controller 사용하기

컨트롤러는 서블릿을 대신해 요청을 처리하는 역할을 한다. 어노테이션:

  • @Controller: 해당 클래스를 컨트롤러로 지정
  • @RequestMapping: 요청 URL을 매핑
1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping("/ex01")
public String ex01(SampleDTO dto) {
	log.info("" + dto);
	return "ex01";
}

@RequestMapping("/ex02")
public String ex02(@RequestParam("str") String name, @RequestParam("num") int age) {
	log.info("name : " + name);
	log.info("age :" + age);
	return "ex02";
}

SampleDTO와 같은 객체를 파라미터로 설정하면, 자동으로 바인딩되어 뷰 페이지로 전달된다.

뷰에서는 다음처럼 사용 가능:

1
2
3
<body>
	${sampleDTO.name}
</body>

여러 파라미터를 배열, 리스트로 받기

같은 이름으로 여러 값이 넘어올 경우 배열이나 리스트로 받을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping("/ex02List")
public String ex02List(@RequestParam("ids") ArrayList<String> ids) {
	log.info("ids : " + ids);
	return "ex02List";
}

@RequestMapping("/ex02Array")
public String ex02Array(@RequestParam("ids") String[] ids) {
	log.info("ids : " + Arrays.toString(ids));
	return "ex02List";
}
This post is licensed under CC BY 4.0 by the author.