package sneeThunder
22.05.23_ 수업 정리(평가일 전날...) 본문
1교시
tip_ 파이널 프로젝트 진행시 프레임워크의 기본기능을 pom.xml에 올려서 화면에 나올때까지 이틀이상 걸리면 안됨!
Q. jdbc연결시 톰켓서버,context.xml에 입력되어 있는거 삭제해도 될까요?
A. 안지워도 됩니다! 충돌안나요~
설정을 두개 해놓고 내 프로젝트에서는(이DAO에서는) 이걸쓰겠어~ 할수있음.
단, servlet프로젝트에서는 가능하지만 스프링 프로젝트에서는 안됨.
-> DI / IOC 개념 때문에 스프링 프로젝트에서는 불가능함!
스프링으로 커넥션하겠어 하면 스프링으로 커넥션 하는거.
하지만 context.xml에 넣어놓고 해도됨.
-> 그림A 가 동작을 하게 하려면 아래그림에 표시한 코드로 데이터 소스를 꺼내와야지 동작함.
또한 아래 코드를 호출하지 않으면 그냥 설정만 한거여서 문제가 되지않음.
스프링 프로젝트 환결설정
1. 설치
방법1_spring 프로젝트를 위한 sts 설치
https://github.com/spring-projects/toolsuite-distribution/wiki/Spring-Tool-Suite-3
GitHub - spring-projects/toolsuite-distribution: the distribution build for the Spring Tool Suite and the Groovy/Grails Tool Sui
the distribution build for the Spring Tool Suite and the Groovy/Grails Tool Suite - GitHub - spring-projects/toolsuite-distribution: the distribution build for the Spring Tool Suite and the Groovy/...
github.com
download 후 zip풀기 - 폴더 중 “sts-3.9.18.RELEASE” 만 잘라서 c:\ 아래에 넣기 - 폴더 아래 sts.exe 실행 - workspace는 z_spring으로 지정함.
Sts 4는 spring boot가 default로 본 수업에서는 사용하지 않음
sts의 경우 따로 추가 설치하지 않아도 되었으나 무슨 이유인지 추가 설치를 해야 Spring MVC Project 템플릿이 보이는 문제가 발생. |
방법2_Plugin 방법
eclipse 켜서 Help > eclipse marketplace..에서 sts검색하고 sts 3설치 후
“Restart Eclipse IDE to apply the software update?”
eclipse 화면 우측 상단 Open Perspective 눌러서 Spring 선택 후 Open
- 설치 오류 자주 발생함. - 설치 오류 뜨면 다시 설치하기도 힘드니 sts 사용을 권함.
confirm
2. sts에 인코딩 설정. progress 탭추가
a. 인코딩 설정
- General > Appearance > Colors and Font - Basic 폴더에 있는 Text Font 클릭 후 우측 Edit버튼으로 글자 크기 바꾸고 Appl
- utf-8 설정할 것들 - 6개
- General > Editors > Text Editors
- General > Workspace
- JSON > JSON Files
- Web > Css Files
- Web > HTML Files
- Web > JSP Files
- automatic update 하지 않음
b.Windows > show view에 들어가서 progress 탭 추가
3. 톰겟 설치
4. 톰켓 서버에 올려놓기
- Windows > Preference > Server > Runtime Environment에서 우측 Add 눌러서 톰캣9.0 - C:\apache-tomcat-9.0.58 추가
- Windows > show view > Servers 누르고 Servers 탭을 좌측 패키지 하단으로 이동시킨 후 톰캣을 서버에 등록( 이후 포트 번호 수정 및 Serve modules without publishing 체크하지 않음 ) - 체크하지 않음
3. Serve modules without publishing 체크하면 metadata 가 아닌 소스코드 위치를 realpath로 사용하는 장점이 있으나 controller 컴파일 위치 확인 및 jstl 인식이 되지 않는 문제로 사용하지 않음.
4. Maven 설치
zip 풀기 - C:\apache-maven-3.8.5 넣기
꼭 메이븐을 설치해야 프로그램이 돌아가느냐? ㄴㄴ
우리가 프로젝트를 만들때 이클립스에서 애초에 메이븐 프로젝트인걸 알고 시작함.
또하나.pom.xml 파일 아래쪽에 보면 그룹이 두개 있음 ( + 메이븐 컴파일러)
그래서 실제로 메이븐설치를 안해도 됨. 하지만 설치를 해주는 이유는
dependency에있는 jar들이 로컬의 Repository에 저장이 되는데
어디에 저장 되냐면 (이클립스 기준)
그러다보니 계정이름을 바꾸거나 한글 또는 띄어쓰기 같은거로 인지가 잘안되는 경우
찾지 못해서 오류가 날 수 있음. 그래서 설정을 통해 내가 원하는곳에 셋팅을 걸고 위치를 지정하는거임.
5. Maven 설정
- 폴더만들기 C:\dev\maven\repository 폴더만들기
- C:\apache-maven-3.8.5\conf 폴더 안에 setting.xml을 수정 후 경로 설정
설정하지 않으면 C:\Users\한글 띄워쓰기\Desktop\empty\apache-maven-3.6.1\repository
<!--localRepository라고 되어 있는 주석 부분 위에 아래와 같이 자신의 repository 폴더 위치 등록하고 저장
<localRepository> C:\dev\maven\repository </localRepository> |
3. Windows > Preference > Maven > User Settings 클릭하고 User Settings: 에서 Browse 눌러서
설치한 Maven의 conf 폴더 안 settings 주소를 넣음
6. xml DTD 설정 (이건 꼭 안 하고 xml 생성시 타이핑 해도 됨)
문서 형식 정의(Document Type Definition, DTD) ->문서 정보
Windows > Preference
- XML > XML Catalog > User Specified Entries 클릭 – 우측 Add 버튼 클릭
- - config
Location : http://mybatis.org/dtd/mybatis-3-config.dtd Key type : Public ID Key : -//mybatis.org//DTD Config 3.0//EN |
2. - Mapper
Location : http://mybatis.org/dtd/mybatis-3-mapper.dtd Key type : Public ID Key : -//mybatis.org//DTD Mapper 3.0//EN |
파일 생성하기 new > xml file > 위치선정및파일명작성(mybatis-config.xml) > create xml file from DTD file 또는 create file using a DTD or XML schema file > Select XML Catalog entry > User Specified Entries |
7. Spring Legacy Project 만들기(progress 탭으로 진행 상태 로딩 체크)
new > Spring Legacy Project 눌러서 Project name은 아무거나 하고
Spring MVC Project 선택해서 Next > alert 창
***** package는 반드시 .으로 구분해서 3단계로 씀 *****
ex) com.kh.finale (★★3단계에서 마지막 패키지명(finale)은 project명과 일치하게★★)
디버깅 쉽게 눈에 띄게 하기 위해 kh.test.first로 생성
- 그렇게 생성 누르면 Progress바가 움직이면서 각종 repository에 library들을 설치하는데 progress탭에서 진행 상황 확인 (완료 되면 다음 단계)
- main 아래 resource에는 각종 mapper 설정 및 datasource(DBMS(Oracle)랑 연결하는 설정)
8. pom.xml 버전 수정
자바 버전 <properties> <java-version>1.11</java-version> <org.springframework-version>5.3.19</org.springframework-version> |
스프링 프레임워크 버전(3.0 이상부터 artifactId 앞에 javax가 붙음.) <!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> |
<configuration> <source>${java-version}</source> <target>${java-version}</target> |
pom.xml 수정 후 꼭!!! 프로젝트 > 오른마우스 > Maven > Update Project > ok 해야함. (alt+ f5) - 깨끗하게 jar모두지우고 다시 받고 싶다면 force… 체크하고 ok |
9. DB 연동 추가
<!-- DB 연동 --> <!-- spring-jdbc, 필수 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${org.springframework-version}</version> </dependency> <!-- ojdbc6 --> <dependency> <groupId>com.oracle.database.jdbc</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.4</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- DBCP --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> - 예전에는 톰켓의 context.xml에서 Connection풀을 관리했다면 지금 부터는 commons-dbcp에서 제공해주는 dbcp기능을 이용할거임. |
10. GSON 추가
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.6</version> </dependency> |
11. JUnit 추가
<!-- version 별 궁합 - Servlet 3.1.0이상이라면 junit은 4.12 이상사용해야함. --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework-version}</version> <scope>test</scope> </dependency> |
pom.xml 수정 후 꼭!!! 프로젝트 > 오른마우스 > Maven > Update Project > ok 해야함. (alt+ f5) - 깨끗하게 jar모두지우고 다시 받고 싶다면 force… 체크하고 ok |
*** web.xml/ root-conrtext.xml / servlet-context.xml 수정 후 꼭!!! ****
server - restart 해주세요 ( 속닥 )
12. DB 연동
root-context.xml
<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource"> <property name="driverClassName" value="oracle.jdbc.OracleDriver" /> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" /> <property name="username" value="scott" /> <property name="password" value="SCOTT" /> </bean> Bean 생성 , Bean 이름은? id="dataSource" |
위 코드에서 생성된 Bean 즉, dataSource는 sqlSessionFactory를 생성할때 property로 사용됨.
mybatis session( sqlSessionFactor) 를 만들때는
DB 연동이 되어있는 dataSousrce도 이용되지만
mybatis-config.xml 파일를 이용해서 정보를 세팅하면서 생성해줌
이렇게 생성된 bean( sqlSessionFactory) 은 sqlSession를 생성할때 생성자의 parameter로 활용(전달)됨.
casspath:
casspath: | src/main/resource |
코드로 나타내면
위 코드가 root-context.xml 코드처럼 바뀌어져 았는걸 DI 라고 불러줌.
어느 시점에 bean객체들을 생성을 하는가? 서버가 StartUp 될때 생성됨.
그래서 동그라미 친 부분에 오류가 있으면 스타트업이 안됨.
또한, mybatis-config.xml 파일안에 mapper파일에도 오류가 있으면 startup이 안됨.
"스프링 프레임워크가 내가 알아서 bean객체들을 생성할테니 너는 신경꺼도돼. "
servlet-context.xml
HomeController
controller에다가 @Controller 넣어주기
톰켓 서버 실행 -> web.xml 실행됨 -> server-context.xml에서 아래 코드 네모박스가 실행 ->
@Controller붙어있는 HomeController 클래스가 new 생성됨.근데 이제 컨트롤러 색상을 곁들어서^^
@Controller |
Bean생성 + controller |
DAO
@Repository
@Repository | Bean생성 + repository(Bean으로 생성) |
데이터베이스를 갔다오면서 데이터에 대한 repository를 관리하는 기능을 가지게 될거야
service
@Service | Bean생성 + service |
@Autowired | Start up 할때 생성한 Beans 중에 MemberDao bean 좀 쓸게 선언만 한거처럼 보이지만 startup할 때 만들어진 객체가 대입되어있음. 그니까 다른곳에서 선언된걸 끌어와 쓰는거임 // @Autowired 어노테이션의 기능 : SqlSession 자료형으로 객체가 만들어진 것이 있다면 찾아서 사용하겠음. |
※import 의 개념 = 소속 ( 길게 -> 짧게적어줄게 다른기능 X typealias랑 비슷)
틈새 자바개념
오류 가능성1 - "선언만 해놓고 사용할수없음."
오류 가능성2 - 실행하면 nullpointException
mybatis-config.xml
-vo를 셋팅안해서 typeAliases 주석처리함.
2교시
* 필수로 알아야 하는것들
1. bean 생성하기
2. 어노테이션
3. 키워드들
-> 스프링 pdf 참조!!! ( 면접가기전에) - 2_spring기초4
Vo에는 어떤 어노테이션이 달릴까,,? @Component
VO
의존성 주입으로 생성
이렇게 생성을 할때 sqlSession를 끌어와 생성함 -> 의존관계 성립
또한 dao 도 service에서 끌어와 사용
이렇게 끌어와 사용을 했을때 MemberDao가 수정이 된다면 미치는 정도는 당연히 있지만
new 해서 생성을 했을때보다는 결합도가 낮다.
@Repository 가 주석처리 되면 dao는 @AutoWired로 끌어다가 사용할 수 없는 상태가 됨.
.하지만 이 시점에 dao는 모름 그렇기 떄문에 MemberDao 객체가 실제로 생성되어있든 안되어있든
코드적으로 매우 독립적으로 돌아가는거 처럼 보임
따라서 DAO에 오류가 나도 의존성주입을 해준 Service에서는 오류가 안날수도 있음.
1개일때 index,name 생략 가능
web.xml에 작성시 장점 - 중복 가능성 낮아짐 , 관리의 편의성 높아짐
단점 - 너무 많아지면 xml파일 관리가 어려움.
DB 연동은 servlet이든 root든 어디에 넣어도 상관없으나 주로 root-context.xml에 넣음
3교시
Bean도 만들고 어노테이션도 만들고 둘다 만들면 안됨.
@Autowired는 철저히 자료형에 의해 가지고 옴.
@Qualifier | 좀더 명확한 애를 가져오고 싶을때 |
찾아서 주석 처리 할 필요없이 여기에서 기능을 넣고 빼고 할수 있음.
4교시 - 교재
5교시
transaction Manager - 순서 상관 없음
강사님이 root-context.xml에 추가시킨거
대부분의 xml 파일에서는 순서 상관없음 .
하지만 mybatis-config.xml에서는 순서 중요함
aop
root-context에tj Namespaces를 누르고 aop 와 tx 체크 하기
<aop:pointcut expression="execution(* kh.spring.myweb..*Dao.*(..))" id="daoMethod"/>
리턴타입 - *
패키지 - kh.spring.myweb
클래스명 - Dao로 끝나는애들한테 적용시켜줘
메소드명 - * (무엇이든 상관없음)
read-only="true" 읽기전용 - 트랜잭션 동작 안함.
<?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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> <!-- DB 연결 --> <!-- DBCP --> <bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource" destroy-method="close"> <property name="driverClassName" value="oracle.jdbc.OracleDriver"/> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/> <property name="username" value="scott"/> <property name="password" value="tiger"/> </bean> <bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis-config.xml"/> </bean> <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSession"> <constructor-arg ref="sqlSessionFactory"></constructor-arg> </bean> <!-- Transaction Manager commit/ rollback 제어 --> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" read-only="true" rollback-for="Exception"/> <tx:method name="insert*" rollback-for="Exception"/> <tx:method name="update*" rollback-for="Exception"/> <tx:method name="delete*" rollback-for="Exception"/> </tx:attributes> </tx:advice> <!-- AOP를 통해서 Transaction 대상을 Pointcut 설정 --> <aop:config> <aop:pointcut expression="execution(* kh.spring.myweb..*Dao.*(..))" id="daoMethod"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethod" id="transactionAdvisor"/> </aop:config> <!-- <bean class="kh.spring.myweb.member.model.dao.MemberDao" id="memberDao"></bean> <bean class="kh.spring.myweb.member.model.service.MemberService" id="memberSrv"></bean> --> <!-- BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl() --> </beans> <!-- jdbc.driver=oracle.jdbc.OracleDriver jdbc.url=jdbc:oracle:thin:@112.220.63.3:1521:xe jdbc.localurl=jdbc:oracle:thin:@localhost:1521:xe jdbc.username=scott jdbc.password=tiger --> |
포인트컷이 어떻게 동작 되는지 로거로 해보는게 더 정확함.
'WebPrograming > 수업정리' 카테고리의 다른 글
22.05.30_수업정리 (0) | 2022.05.30 |
---|---|
22.05.24_수업정리_ (0) | 2022.05.25 |
22.05.20 sping수업(6차시)_ (0) | 2022.05.20 |
22.05.19_spring 수업(5차시)_ (0) | 2022.05.20 |
22.05.18 수업_ spring(4 차시)_myBatis작성(2) (0) | 2022.05.18 |