1213 Spring 프로젝트 생성 & AdminLTE2
새 프로젝트 생성 시 기본 설정
SpringBoard - Spring Legacy Project 추가
pom.xml 설정 바꾸기
pom.xml
maven-compiler-plugin
<source>1.8<source>
<target>1.8<target>
maven Dependencies 추가
Properties -> Deployment Assembly
maven Dependencies 가 없다면,
Add -> Java Build Path 들어가서 추가
외부 라이브러리 추가
pom.xml
test 뒤, dependencies 사이 추가
test version은 4.12로 변경
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 외부 라이브러리 추가 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4 -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4</artifactId>
<version>1.16</version>
</dependency>
<!-- 외부 라이브러리 추가 -->
기존 프로젝트의 4개 파일 복붙해주기
log4j.xml
log4jdbc.log4j2.properties
logback.xml
mybatis-config.xml
로거 네임 바꾸기
src/main/resources
log4j.xml
<!-- Application Loggers -->
<logger name="com.itwillbs.controller">
<level value="debug" />
</logger>
level value 바꾸기
src/test/resources
log4j.xml
<!-- Application Loggers -->
<logger name="com.itwillbs.controller">
<level value="debug" />
</logger>
.NameSpaces 체크
root-context.xml
디비연결 데이터 소스 만들기
root-context.xml
<!-- 디비 연결 정보 - DataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"
/>
<property name="url"
value="jdbc:log4jdbc:mysql://localhost:3306/springdb"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<!-- 디비 연결 정보 - DataSource -->
데이터소스 테스트
com.itwillbs.controller;
DataSourceTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml" }
)
public class DataSourceTest {
//DataSource 객체 가져와서 디비연결 테스트
private static final Logger mylog = LoggerFactory.getLogger(DataSourceTest.class);
//객체 주입
@Inject
private DataSource ds;
@Test
public void 디비연결테스트_dataSource() throws Exception{
mylog.debug(ds+"");
Connection con = ds.getConnection();
mylog.debug(con+"");
}
}
Ctrl + F11
Junit 실행
[CONSOLE]
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
DEBUG: com.itwillbs.controller.DataSourceTest - org.springframework.jdbc.datasource.DriverManagerDataSource@3faf2e7d
INFO : jdbc.connection - 1. Connection opened
INFO : jdbc.audit - 1. Connection.new Connection returned
DEBUG: com.itwillbs.controller.DataSourceTest - net.sf.log4jdbc.sql.jdbcapi.ConnectionSpy@438bad7c
INFO : org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@68267da0: startup date [Tue Dec 13 10:18:39 KST 2022]; root of context hierarchy
debug 2개 잘 나옴
패키지 3개 만들기 (하나는 controller)
com.itwillbs.domain
com.itwillbs.persistence 디비 관련 패키지
com.itwillbs.service
main/resources 밑에 mapper 폴더 만들기
DB 테이블 만들기
한글 필터 걸기
web.xml
<!-- 한글처리 필터 설정 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 한글처리 필터 설정 -->
tomcat 경로 설정
edit 버튼 클릭
/ 로 변경
실행
main/java
HomeController
Run as Server
주소를 localhost:8080/ 로 변경하면 404에러에서 아래와 같은 문구가 뜸
템플릿 적용 해보기
https://github.com/ColorlibHQ/AdminLTE/releases/tag/v2.4.18
Release AdminLTE 2.4.18 · ColorlibHQ/AdminLTE
Release Notes updated jquery-ui to 1.12.1 removed position absoulte from box-tools to avoid overlapping with box-title enhanced tree collapse/expand to avoid flood slide animation on multiple clic...
github.com
zip 다운로드
resource 에 css 상위 폴더를 넣어줌
BoardVO 생성
@Data
public class BoardVO {
private Integer bno;
private String title;
private String content;
private String writer;
private Timestamp regdate;
private int viewcnt;
}
sqlSession 연결
root-context
<!-- mybatis설정(디비 연결, 설정, 매퍼) -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:/mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mappers/**/*Mapper.xml"/>
</bean>
<!-- mybatis 설정(디비 연결, 설정, 매퍼) -->
<!-- 디비 연결 (mybatis 설정 + 자원해제) -->
<bean id="sqlSession"
class="org.mybatis.spring.SqlSessionTemplate"
destroy-method="clearCache">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!-- 디비 연결 (mybatis 설정 + 자원해제) -->
<!-- 다른 패키지 정보를 스캔(객체 bean로 인식 처리) -->
<context:component-scan base-package="com.itwillbs.persistence"/>
<context:component-scan base-package="com.itwillbs.service"/>
<!-- 다른 패키지 정보를 스캔(객체 bean로 인식 처리) -->
BoardDAO (interface) 만들기
public interface BoardDAO {
//서버 시간 정보 조회
public String getTime();
}
BoardDAOImpl 생성 후 오버라이딩
@Repository
public class BoardDAOImpl implements BoardDAO {
//디비 연결 -> bean 주입 (root-context.xml)
@Inject
private SqlSession sqlSession;
//mapper NAMESPACE 정보
private static final String NAMESPACE = "com.itwillbs.mapper.BoardMapper";
@Override
public String getTime(){
return sqlSession.selectOne(NAMESPACE + ".getTime");
}
}
40. XML Schema-based configuration
First up is coverage of the util tags. As the name implies, the util tags deal with common, utility configuration issues, such as configuring collections, referencing constants, and suchlike. To use the tags in the util schema, you need to have the followi
docs.spring.io
매핑된 SQL 구문 살펴보기
https://mybatis.org/mybatis-3/ko/getting-started.html
MyBatis – 마이바티스 3 | 시작하기
mybatis.org
mapper dtd
복붙 하기
boardMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itwillbs.mapper.BoardMapper">
<select id="getTime" resultType="string">
select now()
</select>
</mapper>
BoardDAOTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"file:src/main/webapp/WEB-INF/spring/root-context.xml"}
)
public class BoardDAOTest {
//DAO 객체에 이쓴 디비 호출 메서드 실행
private static final Logger mylog = LoggerFactory.getLogger(BoardDAOTest.class);
//BoardDAO 객체
@Inject
private BoardDAO dao;
@Test
public void 디비연결시간정보() {
mylog.debug(dao.getTime());
}
}
[ CONSOLE ]
DEBUG: com.itwillbs.controller.BoardDAOTest - 2022-12-13 12:39:52
의존 객체 주입
@Inject
=> Java에서 지원하는 어노테이션(특정 프레임워크에 종속적이지 않다)
해당 객체를 찾는 순서
[ 타입 -> @Qualifier -> 이름 -> 실패 ]
@Autowired 동일한 동작 수행 (찾는 순서가 다름)
빌드도구 (Maven/Gradle) 라이브러리 추가 필요
사용 가능 위치 : 멤버 변수, setter(), 생성자, 일반 메서드
@Autowired
=> Spring에서 지원하는 어노테이션
해당 객체를 찾는 순서
[ 타입 -> 이름 -> @Qualifier -> 실패 ]
<context:anotation-config/> 설정값 필요 (스프링 기본 설정값)
사용 가능 위치 : 멤버 변수, setter(), 생성자, 일반메서드
@Resource
=> Java에서 지원하는 어노테이션(특정 프레임워크에 종속적이지 않다)
해당 객체를 찾는 순서
[ 이름 -> 타입 -> @Qualifier -> 실패 ]
<context:anotation-config/> 설정값 필요
사용 가능 위치 : 멤버 변수, setter()
@Qualifier
타입이 동일한 객체(bean)가 여러개 있는 경우 => 스프링 컨테이너 초기화 => Exception
(@Autowired 동일한 타입에 여러 곳 사용)
문제 상황을 해결하기 위해서 객체의 이름을 지정
<context:annotation-config>
<bean id="객체명" class="객체 주소">
<qaulifier value="dao1"/>
</bean>\
</context:annotation-config>
@Inject @Qualifier("Bdao")
private BoardDAO dao;