교육 49일

권재현·2021년 5월 31일
0

교육

목록 보기
35/49

DI 복습

파일샘플스프링 가져오기

1.import - > import

  1. 화면에 보이는 것 클릭

    3.알집파일 넣기 ※ 프로젝트 이름 샘플스프링 중복안됩니다.

    4.X 표시 없고 아래 화면 처럼 되면 성공!!

    5.오른쪽 우클릭 Propertities
    6.JavaBuildPath, Unbound 없애기
    7.edit 들어가서 아파치버전 바꾸기

    8.Apply and Close 누르기

Maven - 통합 라이브러리 관리 및 배포 지원

  • 라이브러리 : 특정 목적에 따라 미리 구현된 프로그램 파일집합

​ ex ) jar 파일 , ear 파일

  • 통합 라이브러리 관리 : 설정된 내용을 기반으로 jar파일을 버전별 보관 및 제공

※프로젝트 import 시 x 표시로 update maven 처리를 했으나, 해결이 안된경우

  • 라이브러리 파일이 정상적으로 다운이 안된경우

  • 이클립스 종료 -> .m2 폴더제거 -> 이클립스 재 실행 -> update maven

jdbc.properties : 데이터베이스 접속정보


-> propertyConfigurer : 접속정보를 key,value로 변환

-> dataSource : 접속설정 객체

-> log : 로그 설정 객체

sqlSession : Session Factory 와 소통-> SessionFactory : DB 연결 객체,SQL Query 관리

개발자는 sqlSession 과 소통

jdbc.properties

#Oracle Database Datasource Properties
################ Oracle DB ##################
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1521:XE 
jdbc.username=TEST
jdbc.password=1234

#Mysql Database Datasource Properties
################ Mysql DB ##################
#jdbc.driverClassName=org.gjt.mm.mysql.Driver
#jdbc.url=jdbc:mysql://127.0.0.1:3306/test
#jdbc.username=test
#jdbc.password=test

#MSSQL Database Datasource Properties
################ MSSQL DB ##################
#jdbc.jdbctype=MSSQL
#jdbc.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
#jdbc.url=jdbc:sqlserver://127.0.0.1:1433;DatabaseName=SID
#jdbc.username=test
#jdbc.password=test

username test로 바꾸기 !!!!
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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>/WEB-INF/spring/jdbc.properties</value>							
			</list>
		</property>
	</bean>
	<!-- dataSource : 접속설정객체 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- log설정: dataSource에 로그 지정(선택사항) -->
    <bean id="dataSourceLog" class="net.sf.log4jdbc.Log4jdbcProxyDataSource">
        <constructor-arg ref="dataSource" />
        <property name="logFormatter">
            <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter">
                <property name="loggingType" value="MULTI_LINE" />
                <property name="sqlPrefix" value="SQL : "/>
            </bean>
        </property>
    </bean>
    <!-- sessionFactory : DB접속 객체 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!-- Mybatis 설정 -->
    	<property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- DB접속 설정 -->
        <!-- <property name="dataSource" ref="dataSource" /> -->
        <property name="dataSource" ref="dataSourceLog" />
        <!-- mapper : 쿼리가 보관된 파일 -->
        <property name="mapperLocations" value="classpath*:mapper/**/*_SQL.xml" />
    </bean>
      <!-- sqlSession : SessionFactory  사용 객체-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>
</beans>

스프링 풀패키지 파일 위치

테스트 폴더 만들기
패키지 TEST
TestController

package com.spring.sample.web.test.controller;

import java.util.HashMap;
import java.util.List;

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

import com.spring.sample.web.test.service.ITestService;

@Controller
public class TestController {
	
	//객체 주입받겠다.
		@Autowired
		public ITestService iTestService;
		
		@RequestMapping(value="/test1")
		
		public ModelAndView test1(ModelAndView mav) throws Throwable  {
			
			List<HashMap<String, String>>list
					=iTestService.getBList();
			
			mav.setViewName("test/test1");
			
			return mav;
		}
}

TestService

package com.spring.sample.web.test.service;

import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.sample.web.test.dao.ITestDao;

@Service
public class TestService implements ITestService {
	//객체 주입받겠다.
	@Autowired
	public ITestDao iTestDao;

	@Override
	public List<HashMap<String, String>> getBList() throws Throwable {
		return iTestDao.getBList();
	}
}

TestDao

package com.spring.sample.web.test.dao;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

//저장소에 접근한다.
@Repository
public class TestDao implements ITestDao {
	
	@Autowired
	public SqlSession sqlSession;
}

ITestDao

package com.spring.sample.web.test.dao;

public interface ITestDao {

}

test1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%> 
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<thead>
		<tr>
			<th>번호</th>
			<th>제목</th>
			<th>작성자</th>
			<th>작성일</th>
		</tr>
	</thead>
	<tbody>
		<c:forEach var="data" items="${list}">
			<tr>
				<td>${data.B_NO}</td>
				<td>${data.B_TITLE}</td>
				<td>${data.B_WRITER}</td>
				<td>${data.B_DT}</td>
			</tr>
		</c:forEach>
	</tbody>
</table>
</body>
</html>

B_SQL.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="B"><!-- namespace: 클래스명과동일 -->
	<!-- id: 메소드명과 동일 -->
	<!-- resultType: row 1줄의 형태를 지정 -->
	<!-- 쿼리 작성 시 ; 이 들어가면 실행 되지 않음 -->
	<select id="getBList" resultType="hashmap">
	SELECT B_NO, B_TITLE, B_WRITER, TO_CHAR(B_DT, 'YYYY-MM-DD')AS B_DT
	FROM B
	ORDER BY B_NO DESC
	</select>
</mapper>

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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>/WEB-INF/spring/jdbc.properties</value>							
			</list>
		</property>
	</bean>
	<!-- dataSource : 접속설정객체 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>
    <!-- log설정: dataSource에 로그 지정(선택사항) -->
    <bean id="dataSourceLog" class="net.sf.log4jdbc.Log4jdbcProxyDataSource">
        <constructor-arg ref="dataSource" />
        <property name="logFormatter">
            <bean class="net.sf.log4jdbc.tools.Log4JdbcCustomFormatter">
                <property name="loggingType" value="MULTI_LINE" />
                <property name="sqlPrefix" value="SQL : "/>
            </bean>
        </property>
    </bean>
    <!-- sessionFactory : DB접속 객체 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<!-- Mybatis 설정 -->
    	<property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- DB접속 설정 -->
        <!-- <property name="dataSource" ref="dataSource" /> -->
        <property name="dataSource" ref="dataSourceLog" />
        <!-- mapper : 쿼리가 보관된 파일 -->
        <property name="mapperLocations" value="classpath*:mapper/**/*_SQL.xml" />
    </bean>
    <!-- sqlSession : SessionFactory  사용 객체-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory" />
    </bean>
</beans>

DB B 테이블 생성

실행 전 서버추가

출력결과

오늘 요약

전체적인 흐름

result type

정리 해놓은 것을 보면서 집에서는 복습하는데 확실히 한번더 하니 흐름이 조금 더 와닿고 오류 란 것도 직접 찾아서 고치니 오후에 수업을 들었을 때보다 이해도가 더 올라갔다. 내일 실습을 하면서 이해도를 더 올리자

profile
호텔리어 출신 비전공자

0개의 댓글