본문 바로가기
코딩수업/AWS 클라우드환경 네이티브

(logger 미완)11/8 웹 제작 - RequestMapping / Inject / 로그 관리 (logger)

by 인생즐겜러 2022. 11. 18.
728x90
반응형

AWS 클라우드환경 네이티브 수업 116 일차

 

 

 

진행

1. 로그 관리 (logger)

 

 

 

 

 

요약

1. @RequestMapping

2. @Inject

3. 로그 관리 (logger)

 

 

 

 

 


 

 

 

 

 

@RequestMapping

 

JSP Servlet 에서는 URL 요청을 web.xml에서 설정해서 매칭시키거나

web.xml에서 FrontController를 매칭 시켜 각 Controller 별로 연결시킨다.

 

하지만 Spring에서는 간편화를 위해 번거로움 없이 각 Controller에서 바로 매칭을 시킬 수 있다.

이때 사용하는 것이 @RequestMapping

 

@RequestMapping의 옵션은 value / method / params / consumes / produces.

이 중 주로 사용하는 건 value와 method.

value : 요청 받을 URL을 설정. 만약 옵션에 아무것도 설정하지 않고 값 한개만 적을 시 value 라고 인식한다.

method : 어떤 요청을 받을지 정의. ( GET, POST, PUT, DELETE 등 )

 

방법은 아래와 같다.

 

@RequestMapping(value = "/hello", method = RequestMethod.GET)

 

 

 

/hello 라는 URI 하나로 method 별로 만든다고 가정했을 때

예시는 아래와 같다. 

 

  • method 별로 각 요청을 적는다
  • method 옵션을 넣지 않고 상위 메소드에 어노테이션 후
    하위 메소드 별로 매핑 어노테이션을 적는다. ( @GetMapping, @PostMapping, @PutMapping, @DeleteMapping )

 

@Controller
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String helloGet(...) {
        ...
    }

    @RequestMapping(value = "/hello", method = RequestMethod.POST)
    public String helloPost(...) {
        ...
    }

    @RequestMapping(value = "/hello", method = RequestMethod.PUT)
    public String helloPut(...) {
        ...
    }

    @RequestMapping(value = "/hello", method = RequestMethod.DELETE)
    public String helloDelete(...) {
        ...
    }
}

 

@Controller
@RequestMapping(value = "/hello")
public class HelloController {

    @GetMapping()
    public String helloGet(...) {
        ...
    }

    @PostMapping()
    public String helloPost(...) {
        ...
    }

    @PutMapping()
    public String helloPut(...) {
        ...
    }

    @DeleteMapping()
    public String helloDelete(...) {
        ...
    }
}

 

 

 

두번째 방법으로 진행 시 추가 url을 넣고 싶다면 아래와 같이 넣으면 된다.

아래의 경우 /hello/addurl 로 접속 요청을 하면 들어갈 수 있다.

 

@Controller
@RequestMapping(value = "/hello")
public class HelloController {    
    @GetMapping("/addurl")
    public String helloGetAdd(...) {
        ...
    }
}

 

 

 

 

 


 

 

 

 

 

@Inject

 

의존 객체 자동 주입이라는 것은

servlet-context.xml 파일에서 일일히 bean 객체 안에 property나 constructor-arg로 객체 설정을 하지 않아도

스프링 컨테이너가 자동적으로 의존 대상 객체를 만들어서

어노테이션이 쓰여진 위치에 필요한 의존성을 주입하는 것을 말한다.

 

방법으로는

Autowired  / Resource  / Inject 가 있는데

그 중 프레임 워크에 구애 받지 않고 사용 할 수 있는 방법이 Inject 이다.

(Resource 는 안 쓰는 게 낫고, Autowired는 Inject 과 방법과 성질이 거의 동일하다. 약간의 차이만 있다.)

 

 

 

Inject가 자동주입될 bean 객체를 찾는 순서는 아래와 같다.

 

타입 => @Named => 이름 => Fail

 

 

 

@Inject를 사용하기 위해서는 maven이나 gradle에 javax 라이브러리 의존성을 추가가 필요하다.

 

<!-- pom.xml-->

<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

 

 

 

사용 예는 아래와 같다.

보통은 타입이 같은 Bean을 먼저 찾는다.

같은 타입의 Bean 객체가 여러 개 있다면 다음은 @Named 속성과 같은 이름인 것을 찾아서 주입하는데

그래도 없다면 예외가 발생.

보통은 @Named 어노테이션을 사용해 정확한 Bean ID를 지정해주는 것이 좋다.

 

	@Inject	
	@Named("sqlSessionFactory")
	private SqlSessionFactory sqlFactory;

 

 

 

 

 


 

 

 

 

 

로그 관리

 

로그 관리를 위한 라이브러리(Log4j) 다운을 먼저 해보자

 

 

 

Log4j는 Java/Kotlin/Scala/Groovy/Clojure 코딩 중에 프로그램의 로그를 기록해주는 라이브러리.

프로그램 실행 시 자동으로 지정한 경로에 로그를 저장하는 기능이 있다.

 

 

 

 

 

먼저, mvnrepository 사이트에 접속한다.

 

 

 

 

 

 

 

 

아래는 로그랑은 별개로 MySQL 커넥터 다운.

 

 

 

 

 

<!-- pom.xml에 코드추가 -->

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-core</artifactId>
		    <version>2.17.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
		<dependency>
		    <groupId>org.apache.logging.log4j</groupId>
		    <artifactId>log4j-api</artifactId>
		    <version>2.17.2</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
		<dependency>
		    <groupId>org.bgee.log4jdbc-log4j2</groupId>
		    <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
		    <version>1.16</version>
		</dependency>
        
		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>8.0.28</version>
		</dependency>
		
		<!-- 오라클 추가 -->
		<dependency>
		   <groupId>jdbc.oracle</groupId>
		   <artifactId>OracleDriver</artifactId>
		   <version>12.1.0.2.0</version>
		   <scope>system</scope>
		   <systemPath>${basedir}/src/main/webapp/WEB-INF/lib/ojdbc10.jar</systemPath>
		</dependency>
        
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis</artifactId>
		    <version>3.5.7</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
		<dependency>
		    <groupId>org.mybatis</groupId>
		    <artifactId>mybatis-spring</artifactId>
		    <version>2.0.6</version>
		</dependency>
		
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-jdbc</artifactId>
		    <version>5.3.16</version>
		</dependency>
		
		
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
		<dependency>
		    <groupId>org.springframework</groupId>
		    <artifactId>spring-test</artifactId>
		    <version>${org.springframework-version}</version>
		    <scope>test</scope>
		</dependency>

 

 

 

 

 

src/main/resources 경로에 받은 파일들을 추가

 

 

 

 

src/main/resources 경로의 log4j.xml파일 코드를 다음과 같이 변경.

 

 

 

 

 

 

root-context.xml의 내용을 다음과 같이 변경.

 

<!-- root-context.xml -->

<?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:aop="http://www.springframework.org/schema/aop"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:jdbc="http://www.springframework.org/schema/jdbc"
   xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
   xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
      http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
      http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">	
      
	<!-- Root Context: defines shared resources visible to all other web components -->
	
	<!-- 자바와 DB연동 -->
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<!--
		<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
		옛날방식(써도 상관없음)
		-->
		<property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property>
		<property name="url" value="jdbc:log4jdbc:mysql://127.0.0.1:3306/gils?useSSL=false&amp;serverTimezone=UTC"></property>
		<property name="username" value="awsuser"></property>
		<property name="password" value="1111"></property>
	</bean>
	
	<!-- SqlSessionFactory는 DB와의 연결과 SQL의 실행에 대한 모든 것을 가진 객체 -->
	<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<!-- <property name="configLocation" value="classpath:/mybatis-config.xml"></property> -->
		<!-- ** 뜻 == 하위폴더가 몇 개든 간에 -->
		<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"></property>
	</bean>
	
	<!-- SqlSession 객체 주입 -->
	<!-- DB연결 종료 후 잡다하게 종료해야 되는거 다 close해줌 -->
	<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="clearCache">
		<constructor-arg name="sqlSessionFactory" ref="SqlSessionFactory"></constructor-arg>
	</bean>
	
</beans>

 

 

 

 

 


 

 

 

 

 

logger

 

 

728x90
반응형

댓글