jnk1m
Foliage IT
jnk1m
전체 방문자
오늘
어제
  • 분류 전체보기 (209)
    • Today I Learned (34)
    • Java (47)
    • Database (15)
    • [NHN Academy] (27)
    • Spring (47)
    • HTML + CSS + JavaScript (11)
    • JSP (3)
    • Node.js (10)
    • React Native (2)
    • 기타 (8)
    • 스크랩 (5)

인기 글

최근 글

티스토리

hELLO · Designed By 정상우.
글쓰기 / 관리자
jnk1m

Foliage IT

Spring

[Spring] Day02 (Code)

2022. 3. 17. 21:28

1. pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.basic</groupId>
	<artifactId>controller</artifactId>
	<name>myspring</name>
	<packaging>war</packaging>
	<version>1.0.0-BUILD-SNAPSHOT</version>
	<properties>
		<java-version>11</java-version>
		<org.springframework-version>5.1.5.RELEASE</org.springframework-version>
		<org.aspectj-version>1.9.3</org.aspectj-version>
		<org.slf4j-version>1.7.30</org.slf4j-version>
	</properties>
	<dependencies>
		<!-- Spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
		
		<!-- lombok: 자바 클래스 getter, setter, toString 생성자 등 자동으로 생성
		https://mvnrepository.com/artifact/org.projectlombok/lombok -->
		<dependency>
		    <groupId>org.projectlombok</groupId>
		    <artifactId>lombok</artifactId>
		    <version>1.18.22</version>
		    <scope>provided</scope>
		</dependency>
		
		<!-- 스프링 테스트:
		https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-test</artifactId>
		    <version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		
		<!--log4j (보안은 무시하고 구버전 사용.) 
		https://mvnrepository.com/artifact/log4j/log4j -->
		<dependency>
		    <groupId>log4j</groupId>
		    <artifactId>log4j</artifactId>
		    <version>1.2.17</version>
		</dependency>
		
		
		<!--  
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>
		-->

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet 
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		-->
		<!-- servelt 3.1로 변경
		https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>javax.servlet-api</artifactId>
		    <version>3.1.0</version>
		    <scope>provided</scope>
		</dependency>
		
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test: 충돌 이슈때문에 4.12로 변경 -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <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>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

2. SampleController

package com.basic.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/sample/") //클래스 레벨에 경로 추가. 요청 주소를 정해놓는 것
            //이 클래스 안에 메서드들의 경로 전에 모두 /sample/ 경로가 추가됨 
public class SampleController {

	@RequestMapping("hello") 
	public String hello() {
		System.out.println("hello page 요청됨.");
		
		return "day02/test"; 
		//위에 /sample/이 생겨서 http://localhost:8080/sample/hello로 요청해야함
	}
	
	/*리퀘스트 매핑에도 속성이 있다. 
	GET, POST
	RM에 요청 주소만 작성하면 GET,POST 방식 다 받아줌. 
	*/
	
	//요청 방식 지정 가능. value="요청 주소", method=요청 방식.
	@RequestMapping(value="test", method= {RequestMethod.GET,RequestMethod.POST})
	public String test() {
		System.out.println("test 요청됨.");
		return "day02/test";
	}
	
	//GET 요청만 받는 어노테이션. 새로 생긴 기능. 
	@GetMapping("test2") 
	public String test2() {
		return "day02/test";
	}
	
	//POST 요청만 받는 어노테이션. 포스트는 주소창에 입력x
	@PostMapping("test3")
	public String test3() {
		return "day02/test";
	}
	
	//여러경로 한번에 적용
	@GetMapping({"test4","test5"}) //test4, test5 뭐를 입력해도 test4 메서드가 실행됨
	public String test4() {
		System.out.println("test4 요청");
		return "day02/test";
	}
	
	@GetMapping("sample?") //?는 뭐가와도 상관 없고 글자 하나를 의미한다. 
	public String test6() {
		return "day02/test";
	}
	
}

 

3. servlet-context

<?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: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">

<!-- Controller, HandlerMapping, ViewResolver는 여기에 세팅 -->

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- css,js, 이미지 등 소스들의 경로를 jsp에서 경로 적을 때
	/resources/ ~라고 작성하면 webapp 밑에 resources 폴더 안에서 찾겠다 지정하기 -->
	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- 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>
	
	<!--해당 패키지를 스캔해라~ @Component, @Contoroller, @Service, @Repository 들이 붙어있는 클래스들 전부 스캔해서 객체 생성 자동으로 해줌
	스프링이 해당 어노테이션이 붙은 클래스들을 객체 생성 (스프링빈으로 등록)해서 스프링이 객체를 관리하게 됨.  -->
	<context:component-scan base-package="com.basic.controller" />
	<context:component-scan base-package="com.test.controller" /> 
	
	
	<!-- 객체 생성:스프링 빈(스프링이 관리하는 객체)으로 등록 
	TestContoller 이름 생략 = new TestController(); 와 동일히다.
	<beans:bean class="com.test.controller.TestController"></beans:bean>-->
	
	
</beans:beans>

 

4. root-context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="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">
	<!-- 서비스와 관련된 것, DAO, DB 관련 등 모든 곳에서 참조해야 되는 설정들 여기에 쓰면 된다. -->
	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!-- Date date = new Date(); 원래 객체 생성 방법. 밑과 동일 -->
	<bean id="date" class="java.util.Date"/>
	<!-- 같은 클래스로 빈 두개 설정: 같은 타입의 객체 두개 생성 -->
	<bean id="day" class="java.util.Date"/>
	<!-- 스프링빈으로 등록. 스프링아~ 객체 생성해서 관리해줘. -->	
	
	<!-- 
	<bean id="chef" class="com.test.sample.Chef"/>  -->
	
	<context:component-scan base-package="com.test.sample"/>
	
	
	
	
	
	
	
</beans>

 

5. TestController

package com.test.controller;


import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.test.sample.Chef;

@Controller
@RequestMapping("/day02/")
public class TestController {

	//의존성 자동 주입: 변수 위에 @Autowired 붙여주면 xml파일에 <bean>으로 등록된 
	//스프링빈(객체) 찾아서 자동으로 주입해준다. 
	//객체 생성은 -context.xml 파일에 bean으로 등록하고 필요한 곳에서 주입 받아 사용 가능
	//먼저 변수의 타입 먼저 확인해서 주입해줌
	@Autowired //어노테이션은 각각 변수마다 하나씩. 
	private Date date; //객체 자동주입
	@Autowired
	private Date day; 
	//date2로 했을 때 오류가 생김. 같은 타입의 빈이 여러개 등록되어 있을때는 
	//변수 이름까지 맞춰줘야 한다. 아이디랑 변수 이름 맞추기.
	//우리끼리 규칙.. 클래스 앞글자 소문자로 해서 그대로 사용하기 
	
	@Autowired
	private Chef chef;
	
	//1. 리턴 타입: String. return "jsp 파일 이름" 	
	@GetMapping("hello")
	public String hello() {
		System.out.println("/test/hello 요청됨!");
		return "day02/test";
	}
	
	//2. 리턴 타입: void. 요청 경로 == jsp 파일 경로
	@GetMapping("hello2")
	public void hello2() {
		System.out.println("/day02/hello2 요청");
		System.out.println("Date: " + date); //객체 사용
		System.out.println("Date2: " + day); //객체 사용
		System.out.println("Chef: "+ chef);
	}
	
	
	
	
}

 

6. Chef 

package com.test.sample;

import org.springframework.stereotype.Component;

import lombok.Data;

@Component //스프링이 관리해야할 객체다~ : component-scan으로 객체 생성 가능
@Data //lombok의 게터세터, 생성자 등등 자동으로 생성해주는 어노테이션.
public class Chef {
	private String name;
}
    'Spring' 카테고리의 다른 글
    • [Spring] Day03 (Code)
    • [Spring] Day03 (Note): 테스트, 스프링 빈, 파라미터 전달, Model
    • [Spring] Day02 (Note): pom.xml 세팅, 컨트롤러, 메서드 리턴 타입, 의존성 주입
    • [Spring] Day01 (Note): 프레임 워크, 초기 세팅, MVC 패턴, 폴더 구조

    티스토리툴바