https://jjaong34.tistory.com/89
[Spring legacy] 스프링 설치 프로젝트 생성
스프링 설치Help > java marketplace 에 들어가서맨위 항목을 install 해준다. 이제 new project에서 other를 누르고 spring legacy project를 선택해준다. Spring MVC Project를 누르고 프로젝트를 생성해준다 만
jjaong34.tistory.com
스프링 레거시 프로젝트 생성 후
maven으로 라이브러리를 관리하려고 한다.
maven
해당 프로젝트에서 [Convert to Maven Project]를 선택하면 pom.xml이 생성된다.
기본적으로 같이 종속시켜주는 라이브러리들 외에 필요한게 있으면
MVN Repository 접속
필요한 라이브러리 검색후
maven 탭에서 해당 탭 소스 복사
<dependencies> 태그로 감싸고 라이브러리 <dependency>를 안쪽에 추가하면된다.
- 예시
<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>
....
</dependencies>
DB 연동 (mybatis)
DB데이터는 mysql emp샘플데이터를 사용함
스프링환경에서 Mybatis연결법
필요한 라이브러리 목록 ( MVN Repository )
- spring jdbc
- spring tx
- commons dbcp
- commons pool
- commons logging
- mybatis
- mybatis spring
위의 라이브러리 들을 모두 pom.xml에 명시한 후
root-context.xml에 bean을 추가해야 한다. ( root-context.xml문서 참조 )
namespaces에 context 체크 후
- 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: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 http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<!-- 아파치의 dbcp라이브러리가 제공하는 BasicDataSource를 생성한다. -->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/my_db" />
<property name="username" value="test" />
<property name="password" value="1111" />
<!-- 동시에 사용할 수 있는 최대 커넥션 수 -->
<property name="maxActive" value="20"></property>
<!-- 커넥션 풀에 반납할 때 최대로 유지되는 커넥션 수 -->
<property name="maxIdle" value="10"></property>
<!-- 커넥션 풀에 반납할 때 최소로 유지되는 커넥션 수 -->
<property name="minIdle" value="10"></property>
</bean>
<!-- mybatis-spring라이브러리가 가지는 FactoryBean객체 생성
이 객체는 DataSource가 있어야 생성할 수 있다. -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 앞서 생성된 DataSource를 현재 객체의 dataSource라는 멤버변수에 저장해야 한다. -->
<property name="dataSource" ref="ds" />
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />
</bean>
<!-- factory를 통해 SqlSession과 같은 객체 생성 -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="factory" />
</bean>
<!-- 필요한 DAO들 정의 -->
<context:component-scan base-package="mybatis.dao" />
</beans>
이제 설정한 파일에 mapper와 dao를 만든다
-mapper
<?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="emp">
<select id="all" resultType="mybatis.vo.EmpVO">
select * from emp
</select>
</mapper>
-dao
package mybatis.dao;
import java.util.List;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import mybatis.vo.EmpVO;
@Component
public class EmpDAO {
@Autowired
private SqlSessionTemplate sqlSession;
public EmpVO[] all() {
EmpVO[] ar = null;
List<EmpVO> list = sqlSession.selectList("emp.all");
ar = new EmpVO[list.size()];
list.toArray(ar);
return ar;
}
}
root-context.xml 에서 component-scan에서 생성시키기 위해
어노테이션으로 { @Component }를 명시해준다.
sqlSession 자동 주입을 위해 { @Autowired }를 명시해준다
이제 비지니스 컨트롤러에서 request에 속성을 담아 해당 jsp로 전달해준다.
- EmpController
package com.sist.ex1;
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 mybatis.dao.EmpDAO;
import mybatis.vo.EmpVO;
@Controller
public class EmpController {
@Autowired
private EmpDAO e_dao;
@RequestMapping("/emp")
public ModelAndView allAction() {
ModelAndView mv = new ModelAndView();
EmpVO[] e_ar = e_dao.all();
mv.addObject("e_ar", e_ar);
mv.setViewName("empAll");
return mv;
}
}
jsp에서 jstl로 해당 데이터를 출력시켜보자
- empAll.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
td, th {
border:1px solid #e2e2e2;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>사번</th>
<th>이름</th>
<th>직종</th>
<th>매니저</th>
<th>입사일</th>
<th>연봉</th>
<th>성과금</th>
<th>부서번호</th>
</tr>
</thead>
<tbody>
<c:if test="${e_ar ne null}">
<c:forEach var="vo" items="${e_ar}">
<tr>
<td>${vo.empno }</td>
<td>${vo.ename }</td>
<td>${vo.job }</td>
<td>${vo.mgr }</td>
<td>${vo.hiredate }</td>
<td>${vo.sal }</td>
<td>${vo.comm }</td>
<td>${vo.deptno }</td>
</tr>
</c:forEach>
</c:if>
</tbody>
</table>
</body>
</html>
- 출력 결과
DB연동이 성공적으로 된 모습이다
마지막으로 spring legacy 중요 동작 순서
- 톰캣 구동시 동작
구동 -> Listener -> root-context.xml -> ds -> factory -> sqlsession -> dao
- 클라이언트 요청시 동작
요청 -> DispacherServlet -> servlet-context.xml -> component-scan -> controller
viewResolver -> views
'Spring' 카테고리의 다른 글
[Spring] 카카오 로그인 (6) | 2024.07.22 |
---|---|
[Spring] 스프링 인터셉터(Spring Interceptor) (0) | 2024.07.19 |
[Spring] db관련 properties 설정 (0) | 2024.07.18 |
[Spring] 한글 처리 (0) | 2024.07.15 |
[Spring] 스프링 설치 프로젝트 생성 (0) | 2024.07.11 |